#C5990. Minimum Days to Complete Tasks with Dependencies
Minimum Days to Complete Tasks with Dependencies
Minimum Days to Complete Tasks with Dependencies
You are given several sets of tasks. Each task may have prerequisites given as dependencies. In one day, you can simultaneously complete all tasks that do not depend on any unfinished tasks. Your goal is to determine the minimum number of days required to complete all tasks. If it is impossible (i.e. there exists a cycle in the dependency graph), output -1
.
The dependency condition can be modeled as follows. There are \( n \) tasks labeled from 1
to n
and \( m \) dependencies. Each dependency is provided as a pair \( (a, b) \), meaning that task \( a \) must be completed before task \( b \) can be started.
Input/Output Format:
Input: The first line contains an integer \( T \) denoting the number of test cases. Several test cases follow. For each test case, the first line contains two integers \( n \) and \( m \)— the number of tasks and the number of dependencies respectively. Then \( m \) lines follow, each containing two integers \( a \) and \( b \) representing a dependency.
Output: For each test case, output a single line indicating the minimum number of days required to finish all tasks, or \( -1 \) if it is impossible.
inputFormat
The input is read from stdin and is formatted as follows:
T n1 m1 a1 b1 a2 b2 ... nT mT a1 b1 ...
Where \( T \) denotes the number of test cases. For each test case, the first line contains \( n \) and \( m \), then \( m \) lines follow, each representing a dependency between two tasks.
outputFormat
For each test case, output a single integer on a new line representing the minimum number of days required to complete all tasks or \( -1 \) if it is impossible.
## sample3
3 2
1 2
2 3
4 3
1 2
2 3
3 4
4 4
1 2
2 3
3 4
4 2
3
4
-1
</p>