← 返回 netflix 的题目列表Topological Sort (Dependency Ordering)
类型:online_judge
Given a directed graph with n nodes labeled 0..n-1 and m directed edges u -> v meaning u must be done before v, do the following:
Determine whether a valid execution order exists (i.e., whether the graph is a DAG).
If it exists, return any valid topological ordering (an array/list of length n). If it does not exist (there is a cycle), return an empty array/list.
Input
Line 1: integer n, number of nodes.
Line 2: integer m, number of edges.
Next m lines: two integers u v describing a directed edge u -> v.
Output
If a topological order exists: print n integers in one line representing a valid order.
Otherwise: print nothing (or an empty line).
Constraints
1 <= n <= 2 * 10^5
0 <= m <= 2 * 10^5
Node ids are in [0, n-1].
Target near-linear time, e.g. O(n+m).
Example
Input
4
3
0 1
1 2
0 3
Output
0 1 3 2