本题若不用并查集会相当麻烦,很有可能超时.
开始我想着:初始化mapping数组为全0,用mapping数组记录下第一组数据,即每个hobby指向第一个人,该组人数变为1.在遍历后面几组数据时,一旦遇到某个hobby对应mapping数组中的值非0,表示这俩人是cluster,然后将当前这个人的其他hobby都指向第一个人,该组人数++,这样一来就需要将该组中前几个已经scanf的hobby重新拿出来指向第一个人,复杂度增加很多,并很麻烦.
此时就需要并查集来帮助简化,引入并查集后,hobby只需要用于判断当前这个人是否有cluster就行,只要有,就将它的cluster作为他的父亲,等全部遍历完,就只剩下并查集的常用末尾做法了.
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=1010;
int mapping[maxn],root[maxn],father[maxn];
int findFather(int x){ //寻找根
int y=x;
while(x!=father[x]){
x=father[x];
}
while(x!=father[y]){
int z=y;
y=father[y];
father[z]=x;
}
return x;
}
void Union(int a,int b){ //合并
int faA=findFather(a);
int faB=findFather(b);
if(faA!=faB){
father[faA]=faB;
}
}
bool cmp(int a,int b){
return a>b;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
memset(mapping,0,sizeof(mapping));
int n,k,count=0,temp;
char c;
scanf("%d",&n);
for(int i=1;i<=n;i++){
father[i]=i;
root[i]=0;
}
for(int i=1;i<=n;i++){
scanf("%d",&k);
scanf("%c",&c);
for(int j=0;j<k;j++){
scanf("%d",&temp);
if(mapping[temp]==0){
mapping[temp]=i;
}else{
Union(mapping[temp],i);
}
}
}
for(int i=1;i<=n;i++){
root[findFather(i)]++;
}
sort(root+1,root+n+1,cmp);
int ans=1;
while(root[ans]!=0){
ans++;
}
ans--;
printf("%d\n",ans);
for(int i=1;i<=ans;i++){
printf("%d",root[i]);
if(i!=ans){
printf(" ");
}
}
return 0;
}