Courses are numbered 0 … n − 1. A line u v means "course u must be taken before course v" (a directed edge u → v). Print an order in which all courses can be taken.
Input
n m
u1 v1 // m directed edges
...
Rules
- Use Kahn's algorithm (in-degrees). Whenever several courses are available (in-degree 0), always take the smallest number first — a
PriorityQueue<Integer>does this. - If not every course can be placed (the prerequisites contain a cycle), print exactly
cycle.
Output — the order on one line, separated by single spaces. For
7 8
5 2
5 0
4 0
4 1
2 3
3 1
6 2
6 4
the output is
5 6 2 3 4 0 1