-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path6.weighted_quick_union.cpp
60 lines (56 loc) · 1.42 KB
/
6.weighted_quick_union.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*************************************************************************
> File Name: 6.union-find.cpp
> Author: Boyu.Ren
> Mail: [email protected]
> Created Time: 一 3/20 14:12:05 2023
************************************************************************/
#include <iostream>
using namespace std;
class UnionSet {
public :
int *father, *size, n;
UnionSet(int n) : n(n) {
size = new int[n + 1];
father = new int[n + 1];
for (int i = 0; i <= n; i++) {
father[i] = i;
size[i] = 1;
}
}
int find(int x) {
if (father[x] == x) return x;
return find(father[x]);
}
void merge(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) return ;
// 把大的顶上去
if (size[pa] < size[pb]) {
father[pa] = pb;
size[pb] += size[pa];
} else {
father[pb] = pa;
size[pa] += size[pb];
}
return ;
}
};
int main() {
ios::sync_with_stdio(false);
int n, m;
cin >> n >> m;
UnionSet u(n);
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
switch (a) {
case 1: u.merge(b, c); break;
case 2: if (u.find(b) == u.find(c)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
}
return 0;
}