#K65897. Graph Connectivity Queries
Graph Connectivity Queries
Graph Connectivity Queries
You are given an undirected graph with n intersections (nodes) and m roads (edges). Each road connects two intersections. After constructing the graph, you are given q queries. In each query, you are given two intersections, and you must determine whether there is a path connecting them.
The problem can be formalized as follows: Let \(G=(V,E)\) be an undirected graph where \(|V|=n\) and \(|E|=m\). For each query \((a,b)\), determine if there exists a path from \(a\) to \(b\).
Input constraints:
\(1 \leq n \leq 10^5\), \(0 \leq m \leq 10^5\), and \(1 \leq q \leq 10^5\).
All nodes are numbered from 1 to n. Use depth-first search (DFS) or union-find (disjoint-set union) to solve the problem efficiently.
inputFormat
The input is given via standard input (stdin) in the following format:
n m u1 v1 u2 v2 ... (m lines) q a1 b1 a2 b2 ... (q lines)
Here, the first line contains two integers, n
and m
. Then follow m
lines each containing two integers u
and v
indicating there is a road between intersections u
and v
.
The next line contains the integer q
, the number of queries, followed by q
lines with two integers each representing the query intersections.
outputFormat
For each query, output a single line containing YES
if there is a path between the two intersections, or NO
if not.
5 4
1 2
2 3
3 4
4 5
3
1 5
2 4
5 1
YES
YES
YES
</p>