Need one fixed order? Keep the ready tasks in a heap, for O(E + V log V)
Kahn's leaves the choice of ready task open, and a problem statement may close it: smallest name first, say. Keep the ready tasks in a heap instead of a deque, so each pop takes the smallest.
Predict
The ready tasks go in a heap, smallest name first. Which task comes third?
Kahn's algorithm with a heapInteractive
on the heap just popped done
heap, heappop takes the smallest:docsfetch
order:empty
Start: fetch and docs need nothing, so they go on the heap.
A heap always keeps its smallest item at index 0, the heapq docs say, and that's what makes this work. On the pipeline, turning the ready list into a heap with heapq.heapify(ready) first, then heapq.heappop in place of popleft and heapq.heappush in place of append, gave ['docs', 'fetch', 'assets', 'compile', 'package', 'test', 'deploy']. Each push and pop costs O(logV), so the sort is O(E+VlogV).
A related question is whether the order is unique. It is exactly when the queue never holds two tasks at once. Another way to say it: there is an arrow from each task in the order to the task right after it.
The editor holds smallest_first with the graph built and the ready tasks listed. Write the loop that takes them from a heap.
Pick an answer above to see the rest
Instructions
1
Finish smallest_first(tasks, needs): keep the ready tasks in a heap, take each with heapq.heappop, and add a released task with heapq.heappush.