GetLists(tasks[1..m], depends[1..m])
1. topological_sort(tasks)
2. cumulative = set()
3. lists = queue()
4. i = 0
5. while |cumulative| != m do
6. temp = set()
7. while depends[i] is a subset of cumulative do
8. temp = temp union {tasks[i]}
9. i = i + 1
10. cumulative = cumulative union temp
11. lists.enqueue(temp)
类似的东西可能会奏效。请注意,lynchpin 正在执行“拓扑排序”以确保您获得终止。另请注意,该算法仅适用于具有有效解决方案的输入集。如果没有解决方案,这将永远循环。很容易修复,但你可以处理。
一个例子:A 不依赖任何东西,B 和 C 依赖于 A,E 依赖于 A 和 C,D 依赖于 C 和 B。
Topological sort: A, B, C, D, E.
cumulative = {}
lists = []
i = 0
|cumulative| = 0 < 5 so...
temp = {}
depends[A] = {} is a subset of {} so
temp = {A}
i = 1
depends[B] = {A} is not a subset of {}, so break
cumulative = {A}
lists = [{A}]
|cumulative| = 1 < 5 so...
temp = {}
depends[B] = {A} is a subset of {A}, so
temp = {B}
i = 2
depends[C] = {A} is a subset of {A}, so
...
你明白了。