#K93712. Unique Puzzle Path

    ID: 38481 Type: Default 1000ms 256MiB

Unique Puzzle Path

Unique Puzzle Path

Marek has organized a treasure hunt game where each puzzle leads to the next clue. Each puzzle's solution is represented as a node in a directed graph, and a directed edge from node u to node v indicates that solving puzzle u leads to puzzle v.

Your task is to determine whether there exists a unique path (i.e. a unique topological ordering) that starts from the unique starting puzzle and covers all N puzzles. If a unique ordering exists, print the puzzles in the order they should be solved. Otherwise, output Impossible.

The graph can be formally described as follows. Given N puzzles and M directed edges, let in_degree denote the number of incoming edges for each puzzle. A valid unique path exists if and only if:

  • There is exactly one puzzle with in_degree = 0 (the start puzzle).
  • During the process of topological sorting, at every step, there is exactly one puzzle with in_degree 0.
  • All puzzles are included in the final ordering.
In terms of LaTeX, the necessary conditions can be summarized as: \[ \text{Unique path exists if } \#\{i \mid in\_degree(i) = 0\} = 1 \quad \text{and at every step } \#\{i \mid in\_degree(i) = 0\} = 1. \]

inputFormat

The input is given via standard input (stdin). The first line contains two integers N and M where N is the number of puzzles (nodes) and M is the number of directed edges. The next M lines each contain two integers u and v indicating a directed edge from puzzle u to puzzle v.

Example:

4 3
1 2
2 3
3 4

outputFormat

The output should be printed to standard output (stdout). Print a single line. If a unique puzzle path exists, output the puzzles in order separated by a single space. Otherwise, print Impossible.

Example:

1 2 3 4
## sample
4 3
1 2
2 3
3 4
1 2 3 4