PAT 1107 Social Clusters (30 分)

#include 
#include 
#include 
using namespace std;
vector<int> father,isroot;
int findfather(int x)
{
    int a=x;
    while(x!=father[x])
        x=father[x];
    while(a!=father[a])
    {
        int z=a;
        a=father[a];
        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;
}
int main()
{
    int n,k,t,cnt=0;
    int course[1001]={0};
    scanf("%d",&n);
    father.resize(n+1);
    isroot.resize(n+1);
    for(int i=1;i<=n;i++)
        father[i]=i;
    for(int i=1;i<=n;i++)
    {
        scanf("%d:",&k);
        for(int j=0;j<k;j++)
        {
            scanf("%d",&t);
            if(course[t]==0)
                course[t]=i;
            Union(i,findfather(course[t]));
        }
    }
    for(int i=1;i<=n;i++)
        isroot[findfather(i)]++;
    for(int i=1;i<=n;i++)
    {
        if(isroot[i]!=0)
            cnt++;
    }
    printf("%d\n",cnt);
    sort(isroot.begin(),isroot.end());
    for(int i=isroot.size()-1;i>=isroot.size()-cnt;i--)
        printf("%d%s",isroot[i],i==isroot.size()-cnt?"":" ");
    return 0;
}

你可能感兴趣的:(PAT 1107 Social Clusters (30 分))