#C11027. Task Order Determination

    ID: 40298 Type: Default 1000ms 256MiB

Task Order Determination

Task Order Determination

You are given a set of tasks numbered from 1 to (N) and a list of dependency pairs. For each dependency ((u, v)) the task (v) can only be performed after task (u) is completed. Your task is to determine a valid task execution order using topological sorting. If a cycle exists such that no valid order is possible, output (-1).

Note: There may be more than one valid task order. In such cases, output the order produced by the standard topological sort algorithm using a first-in-first-out (FIFO) queue. The order should be printed as a space separated list of task numbers. If a valid order cannot be determined because of cyclic dependencies, output a single line with (-1).

inputFormat

The input is read from standard input (stdin) and has the following format:

  • The first line contains a single integer (T) denoting the number of test cases.
  • For each test case, the first line contains two integers (N) and (M) representing the number of tasks and the number of dependency pairs, respectively.
  • Then follow (M) lines, each containing two integers (u) and (v) indicating that task (v) depends on task (u).

outputFormat

For each test case, output a single line. If a valid task order exists, print the tasks in a valid order (space separated). Otherwise, print (-1) if no valid ordering exists due to cyclic dependencies.## sample

2
4 3
1 2
1 3
3 4
4 4
1 2
2 3
3 4
4 2
1 2 3 4

-1

</p>