Smallest Labels First

hard graphs topological-sort heap greedy 1000 ms · 256 MB

Smallest Labels First

You are given a directed acyclic graph with n vertices numbered 1 to n and m edges.

Assign to the vertices the labels 1, 2, ..., n, each label used exactly once, so that for every edge u → v the label of u is smaller than the label of v.

Among all such assignments, find the one whose sequence label[1], label[2], ..., label[n] is lexicographically smallest: vertex 1 should get the smallest label possible, then, among those assignments, vertex 2 should get the smallest label possible, and so on.

Input

The first line contains two integers n and m (1 ≤ n ≤ 2·10^5, 0 ≤ m ≤ 2·10^5).

Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), an edge from u to v. The same edge may appear more than once. The graph is guaranteed to contain no directed cycle.

Output

Print n integers separated by spaces: label[1], label[2], ..., label[n]. Since the graph is acyclic, a valid assignment always exists, and the lexicographically smallest one is unique.

Notes

In the first example, the only edge is 3 → 1. Labelling the vertices in the order 2, 3, 1 (that is, label = 3 1 2) is valid, but label = 2 3 1 is valid as well and gives vertex 1 a smaller label.

In the second example, vertex 1 must come after vertices 3, 4, 2 and 5, so its label is forced to be 5. Vertex 2 must come after 5, so it gets at least 2, and that is achievable.

Example 1

Input

3 1
3 1

Output

2 3 1

Example 2

Input

5 4
4 1
5 2
3 1
2 4

Output

5 2 3 4 1

Hints · reveal one at a time if you're stuck

Hint 1

Labelling vertices in increasing order of number with the smallest available one does not work: with the edge 3 → 1, vertex 1 needs a small label but must wait for vertex 3. Think about which vertex can receive the largest label n instead.

Hint 2

Any vertex that can hold label n must have no outgoing edges. Among those candidates, compare what happens to the whole label sequence if you give n to a smaller-numbered candidate versus the largest one, and argue which choice keeps vertex 1's label small.

Hint 3

So fill the labels from n downwards, always giving the current label to the largest-numbered vertex whose outgoing edges are all already labelled. Process this with a reverse topological sweep: track how many outgoing edges each vertex still has, and a max-heap of the ready vertices. Remember that the output is the label of each vertex, not the order in which they were taken.

report an issue Prefer your own editor? sooks prep 26 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.