#K5696. Path Existence in Directed Graph
Path Existence in Directed Graph
Path Existence in Directed Graph
You are given a directed graph with n nodes and m directed edges. The nodes are labeled from 1 to n. Your task is to determine, for a given list of q queries, whether there exists a path from node u to node v.
In each query, you are provided with two integers u and v. You need to answer "YES" if there exists a path from u to v and "NO" otherwise. A path may traverse several edges, and nodes may have self-loops. The connectivity can be cyclic.
The problem can be formally defined as follows. Given a directed graph \(G=(V,E)\) with \(|V|=n\) and \(|E|=m\), determine for each query \((u,v)\) if \(v\) is reachable from \(u\). That is, determine if there exists a sequence of nodes \(u = x_0, x_1, \dots, x_k = v\) such that \((x_i, x_{i+1}) \in E\) for all \(0 \leq i < k\).
inputFormat
The input is given via standard input (stdin) with the following format:
n m q u1 v1 ... um vm u1 v1 ... uq vq
Here:
n
is the number of nodes.m
is the number of directed edges.q
is the number of queries.- Each of the next
m
lines contains two integers representing a directed edge from nodeu
to nodev
. - Each of the next
q
lines contains two integers representing a query: check if there is a path fromu
tov
.
outputFormat
For each query, output a single line containing either "YES" (if there exists a path from u
to v
) or "NO" (if there is no such path). The output should be printed via standard output (stdout).
5 5 4
1 2
2 3
3 4
4 5
1 5
1 5
1 3
2 5
5 1
YES
YES
YES
NO
</p>