1.合并集合

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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int arr[N];

int find(int x)
{
if (arr[x] != x)
{
arr[x] = find(arr[x]);
}
return arr[x];
}
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
arr[i] = i;
}

while (m--)
{


char c1;
int a, b;
cin >> c1 >> a >> b;
if (c1 == 'M')
{

// a的祖先节点的下标
arr[find(a)] = find(b);
}
else if (c1 == 'Q')
{

if (find(a) == find(b))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
}
}
return 0;
}

2.连通块中点的数量

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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int arr[N];
int size_q[N];

// 递归查找 + 路径压缩
int find(int x)
{
if (arr[x] != x)
arr[x] = find(arr[x]);
return arr[x];
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
arr[i] = i;
size_q[i] = 1;
}

while (m--)
{
string s1;
cin >> s1;
int a, b;
if (s1 == "C")
{
cin >> a >> b;
if (find(a) == find(b))
continue;
else
size_q[find(b)] += size_q[find(a)];
arr[find(a)] = find(b);
} else if(s1 == "Q1")
{
cin >> a >> b;
if(find(a) == find(b))
{
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
} else {
cin >> a;
cout << size_q[find(a)] << endl;

}
}
return 0;
}

3.(难)食物链

240. 食物链 - AcWing题库

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
62
63
#include <iostream>

using namespace std;

const int N = 50010;

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

int find(int x)
{
if (p[x] != x)
{
int t = find(p[x]);
d[x] += d[p[x]];
p[x] = t;
}
return p[x];
}

int main()
{
scanf("%d%d", &n, &m);

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

int res = 0;
while (m -- )
{
int t, x, y;
scanf("%d%d%d", &t, &x, &y);

if (x > n || y > n) res ++ ;
else
{
int px = find(x), py = find(y);
if (t == 1)
{
if (px == py && (d[x] - d[y]) % 3) res ++ ;
else if (px != py)
{
p[px] = py;
d[px] = d[y] - d[x];
}
}
else
{
if (px == py && (d[x] - d[y] - 1) % 3) res ++ ;
else if (px != py)
{
p[px] = py;
d[px] = d[y] + 1 - d[x];
}
}
}
}

printf("%d\n", res);

return 0;
}