← 返回 amazon 的题目列表Topological Sort for Task Scheduling
类型:online_judge
Problem: Task Dependency Ordering
You are given n tasks numbered from 0 to n - 1, and an array prerequisites. Each dependency [a, b] means task b must be completed before task a.
Return any valid order to complete all tasks. If no valid order exists because the dependency graph contains a cycle, return an empty array.
Input Format
The first line contains two integers n and m, the number of tasks and dependencies.
The next m lines each contain two integers a and b, meaning a depends on b.
Output Format
If a valid order exists, print n integers representing one valid ordering.
If no valid order exists, print an empty line.
Constraints
1 <= n <= 10^5
0 <= m <= 2 * 10^5
0 <= a, b < n
Duplicate dependency edges may appear.
Example 1
Input:
4 4
1 0
2 0
3 1
3 2
One valid output:
0 1 2 3
Another valid output:
0 2 1 3
Example 2
Input:
2 2
0 1
1 0
Output:
Example
Input
4 4
1 0
2 0
3 1
3 2
Output
0 1 2 3