Is the Build Order Unique?

medium graphs topological-sort queue 1000 ms · 256 MB

Is the Build Order Unique?

A project has n modules, numbered 1 to n, and m build constraints. Constraint a b means module a must be built strictly before module b. The same constraint may be listed more than once, and a module may even be constrained relative to itself.

A build order is a permutation of 1..n that respects every constraint: for each constraint a b, module a appears earlier in the order than module b.

Determine which of the following holds:

  • no build order exists (the constraints are circular),
  • exactly one build order exists,
  • or more than one build order exists.

If at least one build order exists, also output one of them.

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 a and b (1 ≤ a, b ≤ n): module a must be built before module b. The same pair (a, b) may appear multiple times, and a may equal b.

Output

If no build order exists, print a single line:

CYCLE

Otherwise print two lines. The first is UNIQUE if exactly one build order exists, or NOT UNIQUE if more than one exists. The second line contains n space-separated integers — a permutation of 1..n that is a valid build order. If more than one build order exists, printing any one of them is accepted.

Notes

In the first example, module 1 has no prerequisites and must come first, but after it is built, modules 2 and 3 both become free to build in either order, so several build orders work: both 1 2 3 4 and 1 3 2 4 are accepted.

In the second example every module has exactly one immediate successor, so 1 2 3 is the only build order that respects both constraints.

In the third example modules 1, 2 and 3 depend on each other in a cycle, so no build order exists.

Any correct answer is accepted.

Example 1

Input

4 3
1 2
1 3
3 4

Output

NOT UNIQUE
1 2 3 4

Example 2

Input

3 2
1 2
2 3

Output

UNIQUE
1 2 3

Example 3

Input

3 3
1 2
2 3
3 1

Output

CYCLE

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

Hint 1

A build order is a topological order of the constraint graph. What goes wrong when, at some point, no module has all of its prerequisites already built?

Hint 2

Repeatedly build a module that has no unbuilt prerequisites, and count how many such modules are available at each step. If there is ever more than one choice, the order is not unique; if some modules are never freed, they form a cycle.

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

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