标签:
| Time Limit: 5000MS | Memory Limit: 65536K | |
| Total Submissions: 25383 | Accepted: 12530 |
Description
Input
Output
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
Hint
题意:输入n,m代表有n个帮派,下面输入m行x,y,代表学生x,y同一个帮派,问总共有多少个帮派。
思路:典型的并查集。求出每个的集合,数数这些集合的个数即可
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
using namespace std;
int uset[100010];
int rank[100010];
void makeset(int n)
{
memset(uset,0,sizeof(uset));
for(int i=1;i<=n;i++)
uset[i]=i;
}
int find(int x)
{
if(uset[x]!=x)
uset[x]=find(uset[x]);
return uset[x];
}
void unionset(int x,int y)
{
if((x=find(x))==(y=find(y)))
return;
if(rank[x]>rank[y])
uset[y]=x;
else
{
uset[x]=y;
if(rank[x]==rank[y])
rank[y]++;
}
}
int main()
{
int n,m,i;
int a,b;
int t=1;
while(~scanf("%d %d",&n,&m))
{
if(n==0&&m==0)
break;
makeset(n);
while(m--)
{
scanf("%d %d",&a,&b);
unionset(a,b);
}
int sum=0;
for(i=1;i<=n;i++)
{
if(uset[i]==i)
sum ++;
}
printf("Case %d: %d\n", t++, sum);
}
return 0;
}
POJ 2524-Ubiquitous Religions(并查集)
标签:
原文地址:http://blog.csdn.net/u013486414/article/details/42468097