A workflow of n steps has ordering constraints given as directed edges (u v means u before v). Decide whether there is exactly one valid ordering of all steps. There is exactly one ordering if and only if the graph is acyclic and, at every stage of a topological scan, exactly one step has all its prerequisites already done (never a genuine choice). If the graph is cyclic (no valid ordering) or if more than one ordering exists, the answer is negative.
Line 1: two integers n and m — the number of nodes (labeled 0 through n-1) and the number of directed edges.
Each of the next m lines: two integers u v, a directed edge from u to v (read as: u must come before v).
Print YES if there is exactly one valid ordering, otherwise NO.
Example 1
Input
3 2 0 1 1 2
Expected
YES
Explanation
The chain 0 -> 1 -> 2 forces the single order 0, 1, 2, so it is unique: YES.
Example 2
Input
3 1 0 1
Expected
NO
Explanation
Node 2 is unconstrained, so several orderings exist (e.g. 0,1,2 and 2,0,1): NO.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →