Unclear understanding on Lowest Common Ancestor(LCA) Algorithm

137 views Asked by At

I was trying to learn LCA algorithm O(nlog n) preprocessing and O(log n) query.I am reading it from a russian site with help of google translate.But it is not translating good and I am having some tough time understanding it.Can anybody help me with this ?

This is pseudo code I have taken from that website

int n, l; 

vector <vector <int>> g;

vector <int> tin, tout;

int timer;

vector <vector <int>> up;

void dfs (int v, int p = 0) 
{
  tin [v] = ++ timer;
  up [v] [0] = p;
  for (int i = 1; i <= l; i ++)               /** 3)What is this going
     up [v] [i] = up [up [v] [i-1]] [i-1];

  for (i = 0 size_t; i <g [v] .size (); i ++) 
   {
      to g = int [v] [i];
        if (to! = p)
           dfs (to, v);
   }
   tout [v] = ++ timer;
 }

bool upper (int a, int b) 
{
  return tin [a] <= tin [b] && tout [a]> = tout [b];
}

int lca (int a, int b) 
{
  if (upper (a, b)) return a;
  if (upper (b, a)) return b;

  for (int i = l; i> = 0; --i)              /** 2)What is this going
    if (! upper (up [a] [i], b))
        a = up [a] [i];

  return up [a] [0];

}

int main () {

... Read n and g ...

tin.resize (n), tout.resize (n), up.resize (n);
l = 1;                                    
                                      /** 0)What is 'l' used for ?
while ((1 << l) <= n) ++ l;           /** 1)What is this going
for (int i = 0; i <n; i ++) 
  up [i] .resize (l + 1);
dfs (0);

for (;;) //->query loop
  {
    int a, b; // The current query
    int res = lca (a, b); // Response to a request
  }

}

What I have understood

  • I know we are traversing the graph and storing the in-time and out-time of every vertex.

  • I understand what up[i][j] is It is the 2^j ancestor of i vertex.

  • I understand why up[v][0]=p (because 2^0i.e first ancestor of vertex v is its father only)

  • I understand what upper function do.It decides which vertex occured before A or B.

  • I understand upper(a,b) comes out to be true than lca is A and similarly second step.

What I don't understand is mentioned by me in the pseudo code.Please help me and please confirm if I have understood everything correct or not.

P.S-> Sorry for my english.Not much comfortable with this.

0

There are 0 answers