Efficient algorithm for merging two DAGs

前端 未结 3 1673

I have two weighted DAGs (directed acyclic graphs) and need to merge them into one, so I can get a topological ordering (it could be more than two in some cases). The problem is

3条回答
  •  庸人自扰
    2021-02-05 20:44

    Assuming the vertices are the same for both the graphs if not, just consider

    V = V1 U V1
    

    Lets assume you've got an adjacency list. Now for every vertex v in V1 and V2, you can sort the adjacency list by the vertex the edge leads to (if it's (vertex, weight) pair, sort by vertex). This shouldn't be so expensive since the graph is small, and it would be summation degree(v)*log(degree(v)) which should not be so bad.

    After this you can iterate for all vertices v in V1 and V2, and do a merge sort of the adjacency lists of v in V1 and V2. This is similar to finding union of 2 sorted arrays using merge sort, only that where you'll find an element occurring in both you can choose the larger edge.

提交回复
热议问题