Redundant Connection (Union-Find)
mediumGraphs+20 XPTime limit 2s
A tree with nodes 1 … n had one extra edge added, so the graph now has exactly n edges and one cycle. Find an edge you can remove so the result is a tree again. If several edges qualify, print the one that appears last in the input.
Input:
- line 1:
n - next
nlines: an edgea b(a < b)
Output: the edge to remove, as a b.
Constraints: 3 ≤ n ≤ 10⁵; no repeated edges; the graph is connected.
Think about it: add the edges one by one into a Union-Find. The first edge whose two ends are already connected closes the cycle — and it is the last cycle edge in the input. With path compression each step is almost O(1).
Sample input 1
3 1 2 1 3 2 3
Sample output 1
2 3
Sample input 2
5 1 2 2 3 3 4 1 4 1 5
Sample output 2
1 4
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).