挺简单的题目吧,但是并查集的一个函数写挫了。写demo跑了一下也没啥问题啊,以后还是老实一点吧。
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 1010;
int father[maxn];
int isroot[maxn]={0};
int course[maxn]={0};
int n;
int findf(int x)
{
int a = x;
while(x!=father[x])
{
x=father[x];
}
while(a!=father[a])//path compression
{
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
void onion(int x, int y)//问题所在
{
int xx=findf(x);
int yy=findf(y);
if(xx!=yy)
father[x]=y;
// x=findf(x);
// y=findf(y);
// if(x!=y)
// father[x]=y;
}
void init()
{
for(int i=1;i<=n;i++)
{
father[i]=i;
isroot[i]=0;
}
}
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int i,j,k,x,y;
init();
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d:",&k);
for(j=0;j<k;j++)
{
scanf("%d",&x);
if(course[x]==0)
course[x]=i;
onion(i,findf(course[x]));
}
}
for(i=1;i<=n;i++)
{
isroot[findf(i)]+=1;
}
int ans = 0;
for(i=1;i<=n;i++)
{
if(isroot[i]!=0)
ans++;
}
printf("%d\n",ans);
sort(isroot+1,isroot+n+1,cmp);
for(i=1;i<ans;i++)
printf("%d ",isroot[i]);
printf("%d",isroot[ans]);
return 0;
}