pat甲级1107. Social Clusters (30)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/richenyunqi/article/details/80152842

欢迎访问我的pat甲级题解目录哦https://blog.csdn.net/richenyunqi/article/details/79958195

1107. Social Clusters (30)

时间限制
1000 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

When register on a social network, you are always asked to specify your hobbies in order to find some potential friends with the same hobbies. A "social cluster" is a set of people who have some of their hobbies in common. You are supposed to find all the clusters.

Input Specification:

Each input file contains one test case. For each test case, the first line contains a positive integer N (<=1000), the total number of people in a social network. Hence the people are numbered from 1 to N. Then N lines follow, each gives the hobby list of a person in the format:

Ki: hi[1] hi[2] ... hi[Ki]

where Ki (>0) is the number of hobbies, and hi[j] is the index of the j-th hobby, which is an integer in [1, 1000].

Output Specification:

For each case, print in one line the total number of clusters in the network. Then in the second line, print the numbers of people in the clusters in non-increasing order. The numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
8
3: 2 7 10
1: 4
2: 5 3
1: 4
1: 3
1: 4
4: 6 8 1 5
1: 4
Sample Output:
3
4 3 1

算法设计:

使用并查集,可以开一个数组hobby,元素均初始化为0,hobby[i]记录任意一个喜欢活动 i 的人的编号。在读取数据过程中,如果发现当前的人喜欢的活动i 对应的hobby[i]不为0,表示i 已经有人喜欢,就可以把i 和hobby[i]合并为一个集合。读取数据完成后,定义一个数组result,对于1~N每个人都进行一次++result[findFather[i]],就可以统计出每个集合的人数了。具体实现可见代码。

c++代码:

#include<bits/stdc++.h>
using namespace std;
int hobby[1005],father[1005];
int findFather(int x){//查找父亲结点并进行路径压缩
    if(x==father[x])
        return x;
    int temp=findFather(father[x]);
    father[x]=temp;
    return temp;
}
void unionSet(int a,int b){//合并两个集合
    int ua=findFather(a),ub=findFather(b);
    if(ua!=ub)
        father[ua]=ub;
}
int main(){
    int N;
    scanf("%d",&N);
    iota(father,father+N+1,0);//c++标准库自带函数,将第三个参数赋值给father每一个元素,每赋值一次,第三个参数递增一次,最后赋值完成时,father[i]=i
    for(int i=1;i<=N;++i){//读取数据
        int K,a;
        scanf("%d:",&K);
        while(K--){
            scanf("%d",&a);
            if(hobby[a]==0)//没有人有当前这个爱好
                hobby[a]=i;//i作为第一个有该爱好的人
            else//有人喜欢该爱好
                unionSet(hobby[a],i);//将有同样爱好的两个人合并为一个集合
        }
    }
    int result[N+1]={0};//储存每个集合的人数
    for(int i=1;i<N+1;++i)
        ++result[findFather(i)];
    sort(result,result+N+1,[](const int a,const int b){//从大到小排序
        return a>b;
    });
    int cnt=N+1-count(result,result+N+1,0);//储存集合不为0的集合个数,c++标准库自带的count函数计算result中0的个数
    printf("%d\n",cnt);//输出
    for(int i=0;i<cnt;++i)//输出result前cnt个元素(result已经从大到小排序,输出的都是集合个数不为0的)
        printf("%s%d",i>0?" ":"",result[i]);
    return 0;
}

阅读更多

扫码向博主提问

日沉云起

用最短的代码,写最快的算法
  • 擅长领域:
  • 算法
去开通我的Chat快问
换一批

没有更多推荐了,返回首页