Stable topological sort

前端 未结 6 979
Happy的楠姐
Happy的楠姐 2020-12-29 04:58

Let say I have a graph where the nodes is stored in a sorted list. I now want to topological sort this graph while keeping the original order where the topological order is

6条回答
  •  一整个雨季
    2020-12-29 05:23

    You have insufficient criteria to specify what you're looking for. For instance consider a graph with two directed components.

    1 -> 2 -> 3 -> 4 -> 5
    6 -> 7 -> 8 -> 9 -> 0
    

    Which of the following sorts would you prefer?

    6, 7, 8, 9, 0, 1, 2, 3, 4, 5
    1, 2, 3, 4, 5, 6, 7, 8, 9, 0
    

    The first results from breaking all ties by putting the lowest node as close to the head of the list as possible. Thus 0 wins. The second results from trying to minimize the number of times that A < B and B appears before A in the topological sort. Both are reasonable answers. The second is probably more pleasing.

    I can easily produce an algorithm for the first. To start, take the lowest node, and do a breadth-first search to locate the distance to the shortest root node. Should there be a tie, identify the set of nodes that could appear on such a shortest path. Take the lowest node in that set, and place the best possible path from it to a root, and then place the best possible path from the lowest node we started with to it. Search for the next lowest node that is not already in the topological sort, and continue.

    Producing an algorithm for the more pleasing version seems much harder. See http://en.wikipedia.org/wiki/Feedback_arc_set for a related problem that strongly suggests that it is, in fact, NP-complete.

提交回复
热议问题