0%

并查集

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
#include <bits/stdc++.h>
using namespace std;
int n, m;
int f[10010];
// int find(int x)
// {
// while (x != f[x])
// x = f[x] = f[f[x]];
// return x;
// }
//路径压缩
int find(int x)
{
if(x==f[x])
return x;
return f[x] = find(f[x]);
}
//int find(int x)//或者这样写
//{
// return x == f[x] ? x : (f[x] = find(f[x]));
//}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
f[i] = i;
while (m--)
{
int op, x, y;
cin >> op >> x >> y;
int a = find(x), b = find(y);
if (op == 1)
{
f[a] = b;
}
else
{
if(a==b)
cout << "Y" << endl;
else
cout << "N" << endl;
}
}
}

2 练习

2.1 P1551 亲戚 - 洛谷

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
#include <bits/stdc++.h>
using namespace std;
int n, m, p;
int f[10010];
int find(int x)
{
return x == f[x] ? x : (f[x] = find(f[x]));
}
int main()
{
cin >> n >> m >> p;
for (int i = 1; i <= n; i++)
f[i] = i;
while (m--)
{
int x, y;
cin >> x >> y;
int a = find(x), b = find(y);
f[a] = b;
}
while (p--)
{
int x, y;
cin >> x >> y;
int a = find(x), b = find(y);
if (a == b)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
}

2.2 P 3958 [NOIP 2017 提高组] 奶酪 - 洛谷

  • 本文作者: FXJFXJ
  • 本文链接: https://fxj.wiki/posts/c517589e/
  • 版权声明: 本博客所有文章除特别声明外,均采用 ZERO 许可协议。转载请注明出处!