普通并查集
class UnionFind { vector<int> f; vector<int> cnt; int n;public: UnionFind(int n) : n(n) { f.resize(n); cnt.resize(n); for (int i = 0; i < n; i++) { f[i] = i; cnt[i] = 1; } } int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); } void unite(int x, int y) { x = find(x); y = find(y); if (x == y) return; f[x] = y; cnt[y] += cnt[x]; } bool same(int x, int y) { return find(x) == find(y); } int getCnt(int x) { return cnt[x]; }};
class UnionFind: def __init__(self, n): self.parent = [i for i in range(n)] self.rank = [0 for i in range(n)] def find(self, x): if self.parent[x] == x: return x else: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): x = self.find(x) y = self.find(y) if self.rank[x] > self.rank[y]: self.parent[y] = x else: self.parent[x] = y if self.rank[x] == self.rank[y]: self.rank[y] += 1 def same(self, x, y): return self.find(x) == self.find(y)