题目链接:点击打开链接
#include<cstdio>
#define MAXN 1000 + 10
int fa[MAXN];
int find_set(int i)
{
if(fa[i] == i) return i;
else return (find_set(fa[i]));
}
void union_set(int x,int y)
{
int root_x = find_set(x);
int root_y = find_set(y);
if(root_x != root_y) fa[root_x] = root_y;
}
int main()
{
int n,m;
int x,y;
while(scanf("%d",&n) > 0)
{
if(!n) break;
scanf("%d",&m);
for(int i = 1; i <= n; i++) fa[i] = i;
for(int i = 1; i <= m; i++)
{
scanf("%d%d",&x,&y);
union_set(x,y);
}
int result = 0;
for(int i = 1; i <= n; i++) if(fa[i] == i) result ++;
printf("%d\n",result - 1);
}
return 0;
}
使用rank和路径压缩优化后的代码如下:
#include<cstdio>
#define MAXN 1000 + 10
int fa[MAXN];
struct Node
{
int father;
int rank;
}node[MAXN];
int find_set(int i)
{
if(node[i].father == i) return i;
else{
node[i].father = find_set(node[i].father);
return node[i].father;
}
}
void union_set(int x,int y)
{
int root_x = find_set(x);
int root_y = find_set(y);
if(root_x != root_y){
if (node[root_x].rank > node[root_y].rank)
{
node[root_y].father = root_x;
node[root_x].rank ++;
}
else
{
node[root_x].father = root_y;
node[root_y].rank++;
}
}
}
int main()
{
int n,m;
int x,y;
while(scanf("%d",&n) > 0)
{
if(!n) break;
scanf("%d",&m);
for(int i = 1; i <= n; i++){
node[i].father = i;
node[i].rank = 0;
}
for(int i = 1; i <= m; i++)
{
scanf("%d%d",&x,&y);
union_set(x,y);
}
int result = 0;
for(int i = 1; i <= n; i++) if(node[i].father == i) result ++;
printf("%d\n",result - 1);
}
return 0;
}
但是效果不是很好。。。。下图中109ms为优化后的运行时间。呵呵。。