Algorithm to find lowest common ancestor in directed acyclic graph?

后端 未结 10 838
孤独总比滥情好
孤独总比滥情好 2020-12-02 11:34

Imagine a directed acyclic graph as follows, where:

  • \"A\" is the root (there is always exactly one root)
  • each node knows its parent(s)
  • the no
相关标签:
10条回答
  • 2020-12-02 12:06

    Just some wild thinking. What about using both input nodes as roots, and doing two BFS simultaneously step by step. At a certain step, when there are overlapping in their BLACK sets (recording visited nodes), algorithm stops and the overlapped nodes are their LCA(s). In this way, any other common ancestors will have longer distances than what we have discovered.

    0 讨论(0)
  • 2020-12-02 12:07

    Assume that you want to find the ancestors of x and y in a graph.

    Maintain an array of vectors- parents (storing parents of each node).

    1. Firstly do a bfs(keep storing parents of each vertex) and find all the ancestors of x (find parents of x and using parents, find all the ancestors of x) and store them in a vector. Also, store the depth of each parent in the vector.

    2. Find the ancestors of y using same method and store them in another vector. Now, you have two vectors storing the ancestors of x and y respectively along with their depth.

    3. LCA would be common ancestor with greatest depth. Depth is defined as longest distance from root(vertex with in_degree=0). Now, we can sort the vectors in decreasing order of their depths and find out the LCA. Using this method, we can even find multiple LCA's (if there).

    0 讨论(0)
  • 2020-12-02 12:09

    I also need exactly same thing , to find LCA in a DAG (directed acyclic graph). LCA problem is related to RMQ (Range Minimum Query Problem).

    It is possible to reduce LCA to RMQ and find desired LCA of two arbitrary node from a directed acyclic graph.

    I found THIS TUTORIAL detail and good. I am also planing to implement this.

    0 讨论(0)
  • 2020-12-02 12:18

    I am proposing O(|V| + |E|) time complexity solution, and i think this approach is correct otherwise please correct me.

    Given directed acyclic graph, we need to find LCA of two vertices v and w.

    Step1: Find shortest distance of all vertices from root vertex using bfs http://en.wikipedia.org/wiki/Breadth-first_search with time complexity O(|V| + |E|) and also find the parent of each vertices.

    Step2: Find the common ancestors of both the vertices by using parent until we reach root vertex Time complexity- 2|v|

    Step3: LCA will be that common ancestor which have maximum shortest distance.

    So, this is O(|V| + |E|) time complexity algorithm.

    Please, correct me if i am wrong or any other suggestions are welcome.

    0 讨论(0)
提交回复
热议问题