#K1311. Task Completion with Dependency Constraints
Task Completion with Dependency Constraints
Task Completion with Dependency Constraints
You are given n tasks labelled from 0 to n-1 and a list of d dependency pairs. Each dependency is described by two integers a and b which means that task b cannot be started until task a is completed. Determine if it is possible to complete all tasks while satisfying these dependency constraints.
This problem can be solved using topological sorting. In a dependency graph, if a valid topological ordering exists then all tasks can be completed. In other words, if the graph does not contain any cycle, the answer is YES
; otherwise, the answer is NO
.
The mathematical condition can be stated as follows: A valid ordering exists if and only if \( |\text{sorted_order}| = n \), where \( n \) is the total number of tasks.
inputFormat
The input is given via standard input and has the following format:
n d a1 b1 a2 b2 ... ad bd
Here, the first line contains two integers n (the number of tasks) and d (the number of dependency pairs). Each of the following d lines contains two integers a and b representing a dependency: task b depends on task a.
outputFormat
The output is a single line to the standard output: YES
if it is possible to complete all tasks following the dependency constraints, or NO
if it is not possible.
4 4
1 0
2 0
3 1
3 2
YES