#K41922. Reachability in Directed Graph
Reachability in Directed Graph
Reachability in Directed Graph
You are given a directed graph with n intersections and a list of one-way streets connecting these intersections. Your task is to determine if there is a possibility to travel from a given source intersection to a target intersection, possibly through several intermediate intersections.
You are required to answer multiple queries of the form \( (a, b) \), where for each query you must determine if intersection \(a\) can reach intersection \(b\).
Note: An intersection is always reachable from itself.
Input and output format: The program should read from stdin
and write the results to stdout
.
inputFormat
The input consists of several lines:
- The first line contains two integers \(n\) and \(m\), representing the number of intersections and the number of one-way streets respectively.
- The next \(m\) lines each contain two integers \(u\) and \(v\), indicating a one-way street from intersection \(u\) to intersection \(v\).
- The following line contains an integer \(q\), the number of queries.
- The next \(q\) lines each contain two integers \(a\) and \(b\), representing a query asking whether intersection \(a\) can reach intersection \(b\).
Constraints:
- \(1 \leq n \leq 10^5\)
- \(0 \leq m \leq 10^5\)
- \(1 \leq q \leq 10^5\)
outputFormat
For each query, output a single line containing either YES
if there is a path from the source to the target, or NO
otherwise.
4 4
1 2
2 3
3 4
4 2
3
1 4
4 1
2 4
YES
NO
YES
</p>