題目來源:[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;
}
反思:並查集可以把屬於同一組的元素合併到一起,並可以通過兩個集合的元素的關係,來把兩個集合合併到一起