Daryl
Daryl

Reputation: 3343

How do I find the '5' most weighty paths in a directed acyclic graph?

I have a directed acyclic graph (DAG) with a weight associated with each node. I want to find the top 'n' (e.g. 5) most weighty paths, where a path's weight is defined as the sum of all the weights of it's nodes. How can I accomplish this?

Accuracy is desirable, but can be sacrificed for performance. Potentially, the graph can have 10,000+ nodes and/or edges.

Edit: Weights will be numbers greater than or equal to zero.

Upvotes: 2

Views: 246

Answers (1)

Evgeny Kluev
Evgeny Kluev

Reputation: 24677

  1. Topologically sort the graph.
  2. Associate each graph's node with n-element priority queue (min-heap).
  3. For each node (in sorted order), pop path weights from the priority queue, add node's weight, and pass them to every descendant. When a node receives weight from its parent, it should insert it into associated priority queue.
  4. For each leaf node, pop path weights from the priority queue, add node's weight, and insert them into one common priority queue. After last node is processed, this priority queue contains weights for 'n' most weighty paths. If along with weight, you store back pointers, you can restore these paths.

Upvotes: 2

Related Questions