您的位置:首页 > 其它

poj 2524 求连通分量(并查集模板题)

2015-06-24 22:54 393 查看

求连通分量

Sample Input

10 9
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
10 4
2 3
4 5
4 8
5 8
0 0
Sample Output

Case 1: 1
Case 2: 7

 

# include <iostream>
# include <cstdio>
# include <cstring>
# include <algorithm>
# include <cmath>
# include <queue>
# define LL long long
using namespace std ;

const int MAXN = 50010;
int F[MAXN];
int num[MAXN] ;

int find(int x)//找x的祖先结点
{
if(F[x]==x) return x;
return F[x]=find(F[x]);
}
void bing(int u,int v) //按秩合并
{
int x = find(u);
int y = find(v);
if(x == y)
return ;
if(num[x] >= num[y])
{
F[y] = x;
num[x] += num[y];
}
else
{
F[x] = y;
num[y] += num[x];
}
}
int main()
{
//freopen("in.txt","r",stdin) ;
int n , m ;
int Case = 0 ;
while(scanf("%d %d", &n , &m) != EOF)
{
Case++ ;
if (n == 0 && m == 0)
break ;

int i ;
for(i = 1 ; i <= n ; i++)
{
F[i] = i ;
num[i] = 1 ;
}
int u , v ;
while(m--)
{
scanf("%d %d" , &u , &v) ;
bing(u , v) ;

}
int res = 0 ;
for(i = 1 ; i <= n ; i++)
if (F[i] == i)
res++ ;
printf("Case %d: %d\n" , Case , res) ;
}
return 0;
}
View Code

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: