AcWing 836 837 并查集

题目

AC代码

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
/*并查集,AcWing 836*/

#include <bits/stdc++.h>

using namespace std;

const int N = 100010;

int p[N];

int find(int x){//返回祖宗节点 + 路径压缩
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}

int main(int argc, char const *argv[])
{
int n, m;
cin >> n >> m;

for (int i = 1; i <= n; i ++){
p[i] = i;
}

while(m --){
char op[2];
int a, b;
scanf("%s%d%d", &op, &a, &b);

if (op[0] == 'M') p[find(a)] = find(b);
else{
if (find(a) == find(b)) puts("Yes");
else puts("No");
}

}
}
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
61
/*AcWing 837*/

#include <iostream>

using namespace std;

const int N = 100010;

int n, m;
int p[N], cnt[N];

//返回祖宗节点 + 路径压缩
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}

int main()
{
cin >> n >> m;
// 初始化节点, 下标从1 开始
for (int i = 1; i <= n; i ++ )
{
p[i] = i;
cnt[i] = 1;
}

while (m -- )
{
string op;
int a, b;
cin >> op;

if (op == "C")
{
cin >> a >> b;
// 找到ab 的根节点
a = find(a), b = find(b);
// 如果a和b不相等,那么
if (a != b)
{
p[a] = b;
cnt[b] += cnt[a];
}
}
else if (op == "Q1")
{
cin >> a >> b;
if (find(a) == find(b)) puts("Yes");
else puts("No");
}
else
{
cin >> a;
cout << cnt[find(a)] << endl;
}
}

return 0;
}