Problem 426
Redundant Connection
Medium · 20 pts · Graph, Union Find
Problem
A tree with N nodes (labelled 1 to N) had one extra edge added, so the graph now has N edges and exactly one cycle. Find an edge that can be removed so that the graph becomes a tree again. Every edge on the cycle would work, so print the one that appears last in the input. Union-find processes the edges in order: the first edge whose two ends are already connected closes the cycle, and it is also the last cycle edge in the input.
Input
First line: N. Next N lines: an edge u v.
Output
Print the edge to remove as: u v (as written in the input).
Constraints
3 <= N <= 1000; the graph is a tree plus one extra edge; no repeated edges
Example input
3 1 2 1 3 2 3
Example output
2 3
Explanation
The edges 1-2, 1-3 and 2-3 form a cycle. Removing any of them leaves a tree, and 2 3 is the one that appears last.