Cpp算法-并查集

说明

n, m, q点数、边数、问题数
x, y需要合并的两个数
ufs[]并查集
find(int)查找并查集中一个数的祖先
unionn(int, int)合并两个数所在集合

实现

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
const int maxn = 10010;
int ufs[maxn];
int n, m, x, y, q;

int find(int x)
{
if (ufs[x] != x) return ufs[x] = find(ufs[x]);
return ufs[x] = x;
}

void unionn(int x, int y)
{
int fx = find(x);
int fy = find(y);
if (fx != fy)
{
ufs[fx] = fy;
}
}

int main()
{
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; ++i) ufs[i] = i;
for (int i = 1; i <= m; ++i)
{
scanf("%d %d", &x, &y);
unionn(x, y);
}
scanf("%d", &q);
for (int i = 1; i <= q; ++i)
{
scanf("%d %d", &x, &y);
if (find(x) == find(y)) printf("YES\n");
else printf("NO\n");
}
return 0;
}
作者

TonyCrane

发布于

2019-01-10

更新于

2020-05-05

许可协议