• 1107 Social Clusters 甲级 xp_xht123


    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:

    1. 8
    2. 3: 2 7 10
    3. 1: 4
    4. 2: 5 3
    5. 1: 4
    6. 1: 3
    7. 1: 4
    8. 4: 6 8 1 5
    9. 1: 4

    Sample Output:

    1. 3
    2. 4 3 1

    解题思路:经典的并查集问题,题目描述的每一行都代表一个人所有的爱好,因此存数据的时候对于一个爱好存它拥有的所有的人,然后对于一个爱好中的人,取一个集合中的两个人,先看一下是否在一个集合中,如果是就不管了,如果不是将后者加入到前者的集合中,最后遍历了一遍得到总共的集群的个数和每一个集群的个数输出即可

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. const int N = 1010;
    6. int n;
    7. vector<int>hobby[N];
    8. int p[N];
    9. int res[N];
    10. bool cmp(int a , int b)
    11. {
    12. return a > b;
    13. }
    14. int find(int x)
    15. {
    16. if(p[x] != x) p[x] = find(p[x]);
    17. return p[x];
    18. }
    19. int main()
    20. {
    21. cin >> n;
    22. for(int i = 1;i <= n;i ++) p[i] = i;
    23. for(int i = 1;i <= n;i ++)
    24. {
    25. int k;
    26. scanf("%d:", &k);
    27. for(int j = 0;j < k;j ++)
    28. {
    29. int num;
    30. cin >> num;
    31. hobby[num].push_back(i);
    32. }
    33. }
    34. for(int i = 1;i < N;i ++)
    35. {
    36. for(int j = 1;j < hobby[i].size();j ++)
    37. {
    38. //并查集一般写法
    39. //把后一个加到前一个去
    40. int a = hobby[i][j - 1] , b = hobby[i][j];
    41. a = find(a) , b = find(b);
    42. if(a != b) p[b] = a;
    43. }
    44. }
    45. int si = 0;
    46. for(int i = 1;i <= n;i ++) res[find(i)] ++;//记录每一个群的人数
    47. for(int i = 1;i <= n;i ++) if(res[i]) si ++;
    48. sort(res , res + n + 1 , cmp);
    49. cout << si << endl;
    50. cout << res[0];
    51. for(int i = 1;i < si;i ++) cout << " " << res[i];
    52. return 0;
    53. }

  • 相关阅读:
    Windows 安装 Nginx, 本地访问vue打包项目
    macbook电脑删除app怎么才能彻底清理?
    【对比Java学Kotlin】协程简史
    【C++】单例模式
    微信小程序开发学习笔记
    numpy基础——对array的切片、矩阵加法乘法
    Terraform 华为云最佳实践
    ORM框架SQLAlchemy
    N-pair Loss
    HTTP 请求中的请求方法有哪些常见的类型?
  • 原文地址:https://blog.csdn.net/xp_xht123/article/details/126512723