将LCA解决方案从树扩展到DAG

时间:2019-05-04 16:55:46

标签: algorithm tree directed-acyclic-graphs rmq lowest-common-ancestor

我正在使用通过RMQ求解树中LCA的算法。

它基本上是这样的:

Simple Tree

  • 我们在树上进行欧拉游览,得到3个数组

    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
    
  • 如果我们想要LCA(u,v),我们只需要将L的RMQ从I[u]I[v]

  

示例:LCA(1,2)= L从索引I[1] = 1I[2] = 3的RMQ。

     

L [1:3] = [1,0,1],RMQ [1,0,1] = 0,即索引2,因此 LCA(1,2)= E [2] = 0


我的问题是:如何扩展此解决方案以适合有向无环图

是这样,它不起作用。假设我们有这个DAG:

Directed Acyclic Graph

如果我们计算ELI,我们将得到:

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}

可以看到计算LCA(2,4)是错误的证明,显然应该是2,因为2是4的父代,但是按照该算法,我们将计算:

  

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

     

0的索引为6,因此 LCA(2,4)= E [6] = 0 ,这是错误

有办法使它工作吗?

0 个答案:

没有答案