题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1232http://acm.hdu.edu.cn/showproblem.php?pid=1232
题目解析
基础的并查集问题
代码
1.没有路径压缩的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MIN(a,b) (a<b?a:b)
#define MAX(a,b) (a>b?a:b)
#define Swap(a,b) {(a)=(a)^(b); (b)=(a)^(b); (a)=(a)^(b);}
#define MAXN 65535
#define INF 1e9
int city[1005];
int find(int x){ //不存在路径压缩
int r=x;
while(city[r] != r)
r = city[r];
return r;
}
int main()
{
int n,m;
int i,j;
int a,b;
int count;
while(scanf("%d", &n), n){
scanf("%d", &m);
for(i=1; i<=n; i++) //初始化父亲数组
city[i] = i;
for(i=0;i<m;i++){
scanf("%d%d", &a, &b);
if(find(a)!=find(b))
city[find(a)] = find(b);
}
count = -1;
for(i=1; i<=n; i++){
if(i==city[i])
++count;
}
printf("%d\n", count);
}
return 0;
}
2.有路径压缩的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MIN(a,b) (a<b?a:b)
#define MAX(a,b) (a>b?a:b)
#define Swap(a,b) {(a)=(a)^(b); (b)=(a)^(b); (a)=(a)^(b);}
#define MAXN 65535
#define INF 1e9
int fa[1005];
int find(int x){ //存在路径压缩
if(fa[x]!=x)
fa[x] = find(fa[x]);
return fa[x];
}
int main(){
int m, n;
int x,y,fx,fy;
int i, count;
while(scanf("%d", &n), n){
scanf("%d", &m);
for(i = 1; i<=n; i++) //初始化父亲数组
fa[i] = i;
for(i = 0; i<m; i++){
scanf("%d%d", &x, &y);
fx = find(x);
fy = find(y);
if(fx!=fy)
fa[fx] = fy;
}
for(i=1, count=0; i<=n; i++){
if(fa[i] == i)
count++;
}
printf("%d\n", count-1);
}
return 0;
}