A change-notification system models n components. A directed edge u v means a change in u triggers a re-evaluation of v. When component 0 changes, the trigger cascades along directed edges. Count how many distinct components (other than 0 itself) are eventually re-evaluated. The graph may contain cycles; each reachable component is counted once.
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).
A single integer: the number of distinct nodes reachable from node 0, excluding node 0.
Example 1
Input
4 3 0 1 1 2 0 3
Expected
3
Explanation
From 0 the cascade reaches 1, then 2, and also 3 directly. That is 3 distinct nodes.
Example 2
Input
3 1 1 2
Expected
0
Explanation
Node 0 has no outgoing edges, so nothing downstream is triggered: 0.
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 →