← 返回 openai 的题目列表Topological Sort of Task Dependencies
类型:online_judge
Topological Sort of Task Dependencies
You are given n tasks numbered from 0 to n - 1 and m directed dependency relations. Each relation a b means that task a must be completed before task b can start, i.e. there is a directed edge a -> b.
Output any task execution order that satisfies every dependency.
If the dependency graph contains a cycle and no valid execution order exists, output IMPOSSIBLE.
Input Format
n m
a1 b1
a2 b2
...
am bm
Output Format
If a valid order exists, output n space-separated task IDs.
If a cycle exists, output IMPOSSIBLE.
Constraints
1 <= n <= 200,000
0 <= m <= 500,000
0 <= ai, bi < n
Duplicate edges may appear.
Example 1
Input:
4 3
0 1
0 2
1 3
Output:
0 1 2 3
0 2 1 3 is also valid.
Example 2
Input:
3 3
0 1
1 2
2 0
Output:
IMPOSSIBLE
Example
Input
4 3
0 1
0 2
1 3
Output
0 1 2 3