PAT (Advanced Level) Practice A1107 Social Clusters (30 分)(C++)(甲级)(并查集)

原题链接:A1107 Social Clusters

#include<algorithm>
#include<iostream>
#include<cstdio>
using namespace std;

const int MAX = 1001;
int i, N, K;
int father[MAX], cnt[MAX] = {0}, hobby[MAX] = {0};
int findFather(int x)
{
    int xFa = x, z = x;//xFa为x的根节点
    while(xFa != father[xFa]) xFa = father[xFa];
    while(x != father[x])//路径压缩;让x~xFa上的所有节点都指向xFa
    {
        z = x;
        x = father[x];
        father[z] = xFa;
    }
    return xFa;
}
void unionSet(int a, int b)//合并ab所在的两个集合
{
    int aFa = findFather(a);
    int bFa = findFather(b);
    if(aFa != bFa) father[bFa] = aFa;
}
bool cmp(int a, int b)//从大到小排序
{
  return a > b;
}

int main()
{
    scanf("%d", &N);
    for(i=0; i<MAX; i++) father[i] = i;//初始化每个节点都是一个根节点
    for(i=1; i<=N; i++)
    {
        scanf("%d: ", &K);
        for(int j=0, x; j<K; j++)
        {
            scanf("%d", &x);
            if(!hobby[x]) hobby[x] = i;//第一个拥有该兴趣的人
            unionSet(i, hobby[x]);//合并此人与第一个拥有该兴趣的人的集合
        }
    }
    for(i=1; i<=N; i++) cnt[findFather(i)]++;//计数每个集合中节点的个数
    sort(cnt, cnt+MAX, cmp);//从大到小排序
    for(i=0; i<MAX && cnt[i]; i++);//集合个数
    printf("%d\n%d", i, cnt[0]);//打印
    for(int j=1; j<i; j++) printf(" %d", cnt[j]);
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值