Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
lowest_common_ancestor.cpp File Reference

Data structure for finding the lowest common ancestor of two vertices in a rooted tree using binary lifting. More...

#include <cassert>
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
Include dependency graph for lowest_common_ancestor.cpp:

Classes

class  graph::Graph< T >
 
class  graph::RootedTree
 
class  graph::LowestCommonAncestor
 

Namespaces

namespace  graph
 Graph Algorithms.
 

Functions

static void tests ()
 
int main ()
 

Detailed Description

Data structure for finding the lowest common ancestor of two vertices in a rooted tree using binary lifting.

Algorithm: https://cp-algorithms.com/graph/lca_binary_lifting.html

Complexity:

  • Precomputation: \(O(N \log N)\) where \(N\) is the number of vertices in the tree
  • Query: \(O(\log N)\)
  • Space: \(O(N \log N)\)

Example:
Tree:

            _  3  _
         /     |     \
       1       6       4
     / |     /   \       \
   7   5   2       8       0
           |
           9


lowest_common_ancestor(7, 4) = 3
lowest_common_ancestor(9, 6) = 6
lowest_common_ancestor(0, 0) = 0
lowest_common_ancestor(8, 2) = 6

The query is symmetrical, therefore lowest_common_ancestor(x, y) = lowest_common_ancestor(y, x)

Function Documentation

◆ main()

int main ( void )

Main function

255 {
256 tests();
257 return 0;
258}
static void tests()
Definition lowest_common_ancestor.cpp:234
Here is the call graph for this function:

◆ tests()

static void tests ( )
static

Unit tests

Returns
none
     _  3  _
  /     |     \
1       6       4

/ | / \ \ 7 5 2 8 0 | 9

234 {
235 /**
236 * _ 3 _
237 * / | \
238 * 1 6 4
239 * / | / \ \
240 * 7 5 2 8 0
241 * |
242 * 9
243 */
245 {7, 1}, {1, 5}, {1, 3}, {3, 6}, {6, 2}, {2, 9}, {6, 8}, {4, 3}, {0, 4}};
246 graph::RootedTree t(edges, 3);
248 assert(lca.lowest_common_ancestor(7, 4) == 3);
249 assert(lca.lowest_common_ancestor(9, 6) == 6);
250 assert(lca.lowest_common_ancestor(0, 0) == 0);
251 assert(lca.lowest_common_ancestor(8, 2) == 6);
252}
Definition lowest_common_ancestor.cpp:145
Definition lowest_common_ancestor.cpp:84
Here is the call graph for this function: