您的位置:首页 > 其它

The Suspects(并查集)

2014-07-29 19:02 211 查看
Description

Severeacuterespiratorysyndrome(SARS),anatypicalpneumoniaofunknownaetiology,wasrecognizedasaglobalthreatinmid-March2003.Tominimizetransmissiontoothers,thebeststrategyistoseparatethesuspectsfromothers.

IntheNot-Spreading-Your-SicknessUniversity(NSYSU),therearemanystudentgroups.Studentsinthesamegroupintercommunicatewitheachotherfrequently,andastudentmayjoinseveralgroups.TopreventthepossibletransmissionsofSARS,theNSYSUcollects
thememberlistsofallstudentgroups,andmakesthefollowingruleintheirstandardoperationprocedure(SOP).

Onceamemberinagroupisasuspect,allmembersinthegrouparesuspects.

However,theyfindthatitisnoteasytoidentifyallthesuspectswhenastudentisrecognizedasasuspect.Yourjobistowriteaprogramwhichfindsallthesuspects.

Input

Theinputfilecontainsseveralcases.Eachtestcasebeginswithtwointegersnandminaline,wherenisthenumberofstudents,andmisthenumberofgroups.Youmayassumethat0<n<=30000and0<=m<=500.Everystudent
isnumberedbyauniqueintegerbetween0andn−1,andinitiallystudent0isrecognizedasasuspectinallthecases.Thislineisfollowedbymmemberlistsofthegroups,onelinepergroup.Eachlinebeginswithanintegerkbyitselfrepresentingthe
numberofmembersinthegroup.Followingthenumberofmembers,therearekintegersrepresentingthestudentsinthisgroup.Alltheintegersinalineareseparatedbyatleastonespace.

Acasewithn=0andm=0indicatestheendoftheinput,andneednotbeprocessed.

Output

Foreachcase,outputthenumberofsuspectsinoneline.

SampleInput

1004
212
51013111214
201
2992
2002
15
512345
10
00


SampleOutput

4
1
1


#include<iostream>
usingnamespacestd;
intp[30100];
intfind(intx1)
{if(x1==p[x1])returnx1;
elsereturnp[x1]=find(p[x1]);

}
intmain()
{
intn,m,i,x,y,j;
while(cin>>m>>n,m!=0)
{for(i=0;i<=m;i++)
p[i]=i;
intn1;
for(i=0;i<n;i++)
{cin>>n1;
cin>>x;x=find(x);n1--;
while(n1--)
{

cin>>y;
y=find(y);
p[y]=x;

}
}
x=find(0);y=1;
for(j=1;j<=m;j++)
if(find(j)==x)
y++;

cout<<y<<endl;
}

return0;

}




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