Efficient way to keep only longest paths in a DAG?

377 Views Asked by At

Is there an efficient way to remove all edges that are not part of a longest paths between two nodes in a DAG? For example, for the graph (DAG): (1->2, 2->3, 2->4, 1->3, 1->4) I want to remove the edges 1->3, 1->4 since the paths 1->2->3, 1->2->4 are longer

Edit: so I think the best way is to use topological sort and traverse the array for right to left while aggregating for each node its descendants. Then for each edge a->b we can check whether b is reachable from a using all the other direct descendants of a (and if so we delete the edge). But I didn't find an implementation and I'm not sure it's correct, does anyone aware of an implementation of something like this?

1

There are 1 best solutions below

0
On

The algorithm you suggest is correct, because if an edge is on any longest path, then it must be the longest and only path from its source to target vertices. You can therefore remove any edge that is redundant.

The name for what you are trying to do is "transitive reduction": https://en.wikipedia.org/wiki/Transitive_reduction

While your algorithm works, I don't see that the topological sort is doing you any good. The simple algorithm is to do a search from each vertex to find other ways of reaching its adjacent vertices.