2019-07-16 19:11:38 +00:00
|
|
|
class UFDS {
|
2019-09-04 02:43:14 +00:00
|
|
|
private: vector<int> p, rank;
|
2019-07-16 19:11:38 +00:00
|
|
|
public:
|
|
|
|
UFDS(int N) {
|
2020-09-05 22:17:25 +00:00
|
|
|
p.assign(N+1, 0);
|
2020-04-24 21:39:57 +00:00
|
|
|
for (int i = 0; i <= N; i++) p[i] = i;
|
2020-09-05 22:17:25 +00:00
|
|
|
rank.assign(N+1, 0);
|
2019-07-16 19:11:38 +00:00
|
|
|
}
|
|
|
|
int find_set(int i) { return (p[i] == i) ? i : (p[i] = find_set(p[i])); }
|
|
|
|
bool same_set(int i, int j) { return find_set(i) == find_set(j); }
|
|
|
|
void union_set(int i, int j) {
|
|
|
|
int x = find_set(i), y = find_set(j);
|
2020-06-14 16:15:37 +00:00
|
|
|
if (x == y) return;
|
2019-09-04 02:43:14 +00:00
|
|
|
rank[x] > rank[y] ? p[y] = x : p[x] = y;
|
2019-07-16 19:11:38 +00:00
|
|
|
if (rank[x] == rank[y]) rank[y]++;
|
2019-09-04 02:43:14 +00:00
|
|
|
}
|
2020-09-05 22:17:25 +00:00
|
|
|
};
|