考前训练之并查集:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int MAX = 1010;
vector<int> firsthob;
int father[MAX];
int root[MAX]={0};
void initfather(){
for(int i=0;i<MAX;i++){
father[i]=i;
}
}
int findfather(int x){
if(x==father[x]) return x;
else{
int F=findfather(father[x]);
father[x]=F;
return F;
}
}
void Union(int a,int b){
int Afa=findfather(a);
int Bfa=findfather(b);
if(Afa!=Bfa){
father[Afa]=Bfa;
}
}
bool compare(int a,int b){
if(a>b) return true;
else return false;
}
int main(){
initfather();
int n;
cin>>n;
for(int i=0;i<n;i++){
int numhobs,tempfirsthob;
scanf("%d",&numhobs);
getchar();
getchar();
scanf("%d",&tempfirsthob);
firsthob.push_back(tempfirsthob);
for(int j=0;j<numhobs-1;j++){
int temphob;
scanf("%d",&temphob);
Union(tempfirsthob,temphob);
}
}
for(int i=0;i<n;i++){
int temproot=findfather(firsthob[i]);
root[temproot]++;
}
sort(root,root+MAX,compare);
int count=0;
while(root[count++]!=0);
count--;
cout<<count<<endl;
for(int i=0;i<count;i++){
if(i!=0) printf(" ");
printf("%d",root[i]);
}
}