Problem 628
Course Schedule IV
Medium · 20 pts · Graph, Topological Sort, Depth-First Search
Problem
There are N courses numbered from 1 to N. Each pair (u, v) in the list of prerequisites means course u must be taken before course v. Prerequisites are transitive: if u comes before v and v before w, then u is also a prerequisite of w. The prerequisite graph has no cycles. Answer Q queries (u, v): is u a prerequisite of v? Compute the set of courses reachable from every course once (a search from each node, or a bitset closure), then answer each query in O(1).
Input
The first line contains N, M and Q. The next M lines contain the prerequisite pairs u v. The next Q lines contain the queries u v.
Output
Print YES or NO for each query, one per line.
Constraints
2 <= N <= 100; 0 <= M <= N × (N - 1) / 2; 1 <= Q <= 10000; u != v; the graph is acyclic
Example input
3 2 2 1 2 2 3 1 3 3 1
Example output
YES NO
Explanation
With N = 3 and prerequisites 1 → 2 and 2 → 3, course 1 is needed for 3 through course 2, so the query (1, 3) is YES. The query (3, 1) goes the wrong way, so it is NO.