并查集算法
所谓并查集,就是指对不相交的集合进行“合并” 与 “查询”的问题
处理时注意两点
1、用数组模拟树状结构。
2、查询时可以压缩路径。
蓝桥杯“合根植物”题目代码如下
#include <iostream>
using namespace std;
int pre[1000000];
int a[1010][1010];
int unionSearch(int son)
{
int root = son;
while (root != pre[root]) // 找到son节点的根节点
root = pre[root];
while(son != root) // 路径压缩
{
int tmp = pre[son];
pre[son] = root;
son = tmp;
}
return root;
}
void join(int a, int b, int* total)
{
int x = unionSearch(a);
int y = unionSearch(b);
if(x != y) {
(*total)--;
pre[y] = x;
}
}
int main()
{
int n, m, k;
cin >> m >> n;
int now = 1;
int total = n * m;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
pre[now] = now;
a[i][j] = now++;
}
}
cin >> k;
while (k--) {
int a, b;
cin >> a >> b;
join(a, b, &total);
}
cout << total;
return 0;
}