说来惭愧啊。。现在才会并查集。我竟然给我妈妈讲明白并查集怎么回事了- -
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#define maxx 50010
int set[maxx];
int find(int x)
{
return x == set[x] ? x : (set[x] = find(set[x]));
}
int main()
{
int n, m;
int kase = 0;
while (cin >> n >> m && (n || m))
{
for (int i = 1; i <= n; i++)
{
set[i] = i;
}
for (int i = 0; i < m; i++)
{
int a, b;
scanf("%d %d", &a, &b);
int c = find(a), d = find(b);
if (c != d){ set[c] = d; }
}
int cnt = 0;
for (int i = 1; i <= n; i++)
{
if (set[i] == i) cnt++;
}
cout << "Case " << ++kase << ": " << cnt << endl;
}
}
本文通过一个简单的并查集算法示例介绍了如何实现并查集的基本操作,包括查找根节点和合并集合。并查集是一种用于处理一些不交集的合并及查询问题的数据结构,在解决诸如连通性问题等方面非常有用。
267

被折叠的 条评论
为什么被折叠?



