您的位置:首页 > 理论基础 > 数据结构算法

hdu 1232 畅通工程(数据结构:并查集)

2014-07-20 16:37 232 查看
并查集+路径压缩

注意城市编号从1到n,如果初始化时从0到n-1就坑了!!!

代码如下:

#include <cstdio>
#include <iostream>
#define LL long long
#define MAXN 10010
using namespace std;

int p[MAXN];

int find(int x) {
return x==p[x] ? x : p[x] = find(p[x]);
}

int main(void) {
int n, m, i, x, y;
LL cnt;
while(scanf("%d", &n) && n) {
scanf("%d", &m);
for(i=1; i<=n; ++i)
p[i] = i;

for(i=0; i<m; ++i) {
scanf("%d%d", &x, &y);
x = find(x);
y = find(y);
if(x != y)
p[x] = y;
}
cnt = 0;
for(i=1; i<=n; ++i)
if(p[i] == i)
cnt++;
cout << cnt-1 << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: