Topological Sort
Halvard Build now has to publish the running order for a plan it has already accepted, so there are no circles in it. Each declaration says one job must finish before another starts. Usually several jobs are free to run at any moment, and the customer wants a printed schedule that never changes between runs, so the tie-break is fixed by policy: whenever more than one job could go next, the lowest-numbered one goes.
Task: Print the running order of all the jobs.
Input
The first line holds two integers separated by a space: n, the number of jobs labelled 0 to n-1, and m, the number of declarations. Each of the next m lines holds two integers u v, meaning job u must finish before job v starts. m may be 0. The declarations never form a circle.
Output
One line holding all n job numbers separated by single spaces. Every job appears exactly once, and no job appears before a job it waits for. When several jobs are free to go next, the lowest-numbered of them comes first.
Example:
Input:
4 4
0 1
0 2
1 3
2 3
Output:
0 1 2 3
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in