Problem 175
Path Exists in Graph
Easy · 10 pts · Graph, Depth-First Search, Union Find
Problem
You are given an undirected graph with N nodes and M edges, and two nodes S and D. Decide whether there is a path from S to D, following edges in either direction. A node always has a path to itself. Run BFS or DFS from S and check whether D is visited, or use union-find to merge the ends of every edge and check whether S and D end up in the same set.
Input
First line: integers N (nodes, labelled 1..N) and M (edges). Next M lines: an edge u v. Last line: integers S and D.
Output
Print YES or NO.
Constraints
1 <= N <= 200000; 0 <= M <= 200000
Example input
3 3 1 2 2 3 3 1 1 3
Example output
YES
Explanation
With the edges 1-2, 2-3 and 3-1, node 1 can reach node 3 directly (or through node 2), so the answer is YES.