#K35777. Task Scheduler with Dependency Checking

    ID: 25607 Type: Default 1000ms 256MiB

Task Scheduler with Dependency Checking

Task Scheduler with Dependency Checking

You are given several tasks numbered from 1 to \(N\), along with a list of dependencies between them. Each dependency is given as a pair \((u, v)\), which means that task \(u\) must be completed before task \(v\) can start.

Your task is to determine a valid order in which all tasks can be completed. A valid order is one in which for every dependency \((u, v)\), task \(u\) comes before task \(v\). If there is a cycle (i.e. no valid order exists), output NO.

The condition for a valid ordering can be formally stated as: if \(\text{result}\) is the ordering produced then \(\left|\text{result}\right| = N\). Otherwise, the dependency graph contains a cycle.

inputFormat

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

T
N M
u1 v1
u2 v2
... (M lines)
... (repeat for T test cases)

Where:

  • T is 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 dependencies, respectively.
  • Each of the next M lines contains two integers u and v, representing a dependency that task u must be completed before task v.

outputFormat

For each test case (in the same order as input), output a single line:

  • If a valid order exists, output N space-separated integers representing a valid task order.
  • If no valid order exists due to a cycle, output NO.

The output should be written to standard output (stdout).

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