A task graph has n tasks. A directed edge u v means task u must be completed before task v. Given a target task t, count how many distinct tasks are ancestors of t — that is, tasks from which t is reachable by following directed edges (not counting t itself). These are exactly the tasks that must be finished, directly or transitively, before t can run. The graph may contain cycles.
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).
The final line: a single integer t, the target task.
A single integer: the number of distinct nodes from which t is reachable, excluding t.
Example 1
Input
4 3 0 1 1 2 3 2 2
Expected
3
Explanation
t=2. Node 1 reaches 2 directly, node 0 reaches 2 via 1, node 3 reaches 2 directly. That is 3 ancestors.
Example 2
Input
3 1 0 1 0
Expected
0
Explanation
t=0 has no incoming path from any node, so it has 0 ancestors.
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 →