PAT——A1107 Social Clusters(并查集)

题目链接:

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;
#define maxn 1010
int father[maxn];
int isRoot[maxn]={0};
int course[maxn]={0};
typedef long long ll;
void init(int n)
{
   for(int i=1;i<=n;i++)
   {
       father[i]=i;
   }
}
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;
    }
}
bool cmp(int a,int b)
{
    return a>b;
}
int main()
{
    int n;
    //init();
    scanf("%d",&n);
    init(n);
    for(int j=1;j<=n;j++)
    {
        int a;
        scanf("%d:",&a);
        for(int i=1;i<=a;i++)
        {
            int h;
            scanf("%d",&h);
            if(course[h]==0)
            {
                course[h]=j;
            }
            Union(j,findFather(course[h]));
        }
    }
    for(int i=1;i<=n;i++)
    {
            isRoot[findFather(i)]++;
    }
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        if(isRoot[i]!=0)
            ans++;
    }
    printf("%d\n",ans);
    sort(isRoot+1,isRoot+1+n,cmp);
    for(int i=1;i<=ans;i++)
    {
        printf("%d",isRoot[i]);
        if(i<ans)
            printf(" ");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42232118/article/details/82314813