problems / 117

Alice's Chore List

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

Alice's Chore List

Alice has n chores, numbered 1 to n, that she must all finish today. Bob, who is in charge of the household rules, imposes m ordering rules: a rule a b means chore a must be done at some point before chore b. Alice has to do the chores one at a time, in some order that respects every rule.

Among all orders that respect every rule, Alice — being Alice — wants the one that comes first alphabetically by chore number: the order whose sequence of chore numbers is lexicographically smallest. Help her find it, or tell her that Bob's rules are impossible to satisfy.

A sequence x_1, x_2, ..., x_n is lexicographically smaller than y_1, y_2, ..., y_n if, at the first index where they differ, x has the smaller value.

Input

The first line contains two integers n and m (1 ≤ n ≤ 2·10^5, 0 ≤ m ≤ 2·10^5): the number of chores and the number of rules.

Each of the next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b): chore a must be done before chore b. The same rule may appear more than once.

Output

If no order respects every rule, print a single line IMPOSSIBLE.

Otherwise print n integers: the lexicographically smallest valid order of chore numbers, separated by spaces.

Notes

In the first example, chore 1 needs both chore 2 and chore 3 done first, while chore 4 has no requirements at all. At the start the available chores are 2, 3 and 4, so Alice does chore 2 first. Now 3 and 4 are available, and 3 is smaller, so she does chore 3 next. That finally unlocks chore 1, but 1 is still smaller than the untouched chore 4, so she does chore 1 before chore 4: the order is 2 3 1 4.

In the second example, chore 1 needs chore 2 done first and chore 2 needs chore 1 done first, so neither can ever go first.

Example 1

Input

4 2
2 1
3 1

Output

2 3 1 4

Example 2

Input

2 2
1 2
2 1

Output

IMPOSSIBLE

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

Hint 1

Think of the rules as ordering constraints on a graph. At any moment, which chores are allowed to come next, and which of those should Alice choose to keep the order as small as possible?

Hint 2

Use a topological sort where the set of ready chores is kept in a min-heap, always taking the smallest one. If fewer than n chores get placed, the rules contain a cycle and the answer is IMPOSSIBLE.

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

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