Problem 165
Detect Cycle in an Undirected Graph
Medium · 20 pts · Graph, Depth-First Search, Union Find
Problem
You are given an undirected graph with N nodes and M edges, with no self-loops and no repeated edges. Decide whether it contains a cycle: a path that starts and ends at the same node, uses at least three nodes and does not repeat an edge. The graph may be disconnected. Union-find is a simple method: process the edges one by one, and if an edge connects two nodes that are already in the same set, it closes a cycle. A DFS that finds an already-visited node other than the parent works as well.
Input
First line: integers N (nodes, labelled 1..N) and M (edges). Next M lines: an edge u v.
Output
Print YES or NO.
Constraints
1 <= N <= 100000; 0 <= M <= 200000
Example input
3 3 1 2 2 3 3 1
Example output
YES
Explanation
The edges 1-2, 2-3 and 3-1 form the loop 1 → 2 → 3 → 1, so the graph contains a cycle: YES.