Problem 281
Is Graph a Valid Tree
Medium · 20 pts · Graph, Union Find, Depth-First Search
Problem
You are given an undirected graph with N nodes and M edges. Decide whether it is a tree: it must be connected (every node can reach every other) and contain no cycles. A graph on N nodes is a tree exactly when it has N - 1 edges and is connected. So first check that M = N - 1, then check connectivity with BFS, DFS or union-find. A single node with no edges is a tree.
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; no self-loops or repeated edges
Example input
5 4 1 2 1 3 1 4 2 5
Example output
YES
Explanation
There are 5 nodes and 4 edges, which is N - 1. Node 1 connects to 2, 3 and 4, and node 2 connects to 5, so every node is reachable and there is no cycle. The answer is YES.