1

I'm using the algorithm that solves LCA in a tree using RMQ.

It basically works like this:

Simple Tree

  • We perform an Euler tour on the tree, getting 3 arrays

    E = {0,1,0,2,0} //the vertexes in the order they were visited
    L = {0,1,0,1,0} //the levels of each of these vertexes
    I = {0,1,3}     //index of the first ocurrence of each vertex
    
  • If we want the LCA(u,v), we just need to get the RMQ of L from I[u] to I[v].

example: LCA(1,2) = RMQ of L from index I[1] = 1 to I[2] = 3.

L[1:3] = [1,0,1], RMQ[1,0,1] = 0, which is index 2, so the LCA(1,2) = E[2] = 0.


My question is: how do I extend this solution to fit a Directed Acyclic Graph?

The way it is, it doesn't work. Suppose we have this DAG:

Directed Acyclic Graph

If we compute E, L and I, we'll have:

E = {0,1,3,1,4,1,0,2,4,2,5,2,0}
L = {0,1,2,1,2,1,0,1,2,1,2,1,0}
I = {0,1,7,2,4,10}

And the proof it is wrong can be seen calculating LCA(2,4), which should obviously be 2, since 2 is 4's parent, but following the algorithm, we would compute:

RMQ( I[2] : I[4] ) = RMQ(7,4) = RMQ(4,7) = RMQ( {2,1,0,1} ) = 0

0 has index 6, so LCA(2,4) = E[6] = 0, which is wrong.

Is there a way to make it work?

Daniel
  • 7,357
  • 7
  • 32
  • 84

0 Answers0