题目来源:[NWPU][2014][TRN][12]并查集 E 题
http://vjudge.net/contest/view.action?cid=50731#problem/E
作者:npufz
题目:
Description
You know that there are n students in your university (0 < n <= 50000). It is infeasible for you to ask every student their religious beliefs. Furthermore, many students are not comfortable expressing their beliefs. One way to avoid these problems is to ask m (0 <= m <= n(n-1)/2) pairs of students and ask them whether they believe in the same religion (e.g. they may know if they both attend the same church). From this data, you may not know what each person believes in, but you can get an idea of the upper bound of how many different religions can be possibly represented on campus. You may assume that each student subscribes to at most one religion.
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
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
int parent[50005];
int sum[50005];
int getparent(int a)
{
if(a==parent[a])
return a;
int t;
t=getparent(parent[a]);
parent[a]=t;
return parent[a];
}
int mergege(int a,int b)
{
int pre1,pre2;
pre1=getparent(a);
pre2=getparent(b);
if(pre1==pre2) return 0;
if(sum[pre1]>sum[pre2])
{
parent[pre2]=pre1;
sum[pre1]+=sum[pre2];
return 0;
}
parent[pre1]=pre2;
sum[pre2]+=sum[pre1];
return 0;
}
int main()
{
int n,cas,i,j,k,cnt=1,stu1,stu2,ma,pre,prea;
while(scanf("%d%d",&n,&cas),n!=0&&cas!=0)
{
for(i=1;i<=n;i++)
{
parent[i]=i;
sum[i]=1;
}
for(i=0;i<cas;i++)
{
scanf("%d%d",&stu1,&stu2);
mergege(stu1,stu2);
}
ma=n;
bool flag=true;
//cout<<"ok"<<endl;
for(i=1;i<=n;i++)
{ //cout<<"ok"<<endl;
pre=getparent(i);
if(flag)
{
ma=ma-sum[pre]+1;
prea=pre;
flag=false;
}
else
{
if(pre!=prea)
{
ma=ma-sum[pre]+1;
parent[pre]=prea;
}
}
}
printf("Case %d: %d\n",cnt,ma);
cnt++;
}
return 0;
}
反思:并查集可以把属于同一组的元素合并到一起,并可以通过两个集合的元素的关系,来把两个集合合并到一起