← 返回 meta 的题目列表Union Find Implementation
类型:online_judge
Implement a Union Find (Disjoint Set) data structure that supports the following operations:
find(x) - Returns the representative of the set containing element x.
union(x, y) - Merges the sets containing elements x and y.
Requirements:
For the find(x) operation, use path compression for optimization.
For the union(x, y) operation, use rank union for optimization.
Provide a function solve(operations) where operations is a list of operations, each being:
('union', x, y): Merge sets containing x and y.
('find', x): Return the representative of the set containing x.
Initially, each element is its own set.
Example Test Cases:
Input:
operations = [
('union', 1, 2),
('union', 3, 4),
('find', 1),
('find', 3),
('union', 2, 3),
('find', 4)
]
Output:
[2, 4, 4]
Constraints:
1 <= x, y <= 100,000
Number of operations <= 10^5
Provide the representative of the set in the output.
Example
Input
6
union 1 2
union 3 4
find 1
find 3
union 2 3
find 4