鱼C论坛

 找回密码
 立即注册
查看: 2322|回复: 0

[技术交流] PTA A_1107 Social Clusters

[复制链接]
发表于 2020-2-15 11:24:47 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
传送门:https://pintia.cn/problem-sets/9 ... /994805361586847744

解:
并查集
  1. #include<cstdio>
  2. #include<algorithm>

  3. using namespace std;

  4. int father[1010], hobby[1010] = {0};

  5. int find_root(int n)
  6. {
  7.     int r = n;

  8.     while (r != father[r])
  9.         r = father[r];
  10.    
  11.     while (n != father[n])
  12.     {
  13.         int z = n;
  14.         n = father[n];
  15.         father[z] = r;
  16.     }

  17.     return r;
  18. }

  19. void Union(int a, int b)
  20. {
  21.     if (find_root(a) != find_root(b)) father[father[b]] = father[a];
  22. }

  23. bool cmp(int a, int b)
  24. {
  25.     return a > b;
  26. }

  27. int main(void)
  28. {
  29.     int n;

  30.     scanf("%d", &n);
  31.     for (int i = 1; i <= n; i++)
  32.     {
  33.         father[i] = i;

  34.         int m;
  35.         scanf("%d:", &m);
  36.         while (m--)
  37.         {
  38.             int k;
  39.             scanf("%d", &k);

  40.             if (hobby[k])
  41.                 Union(hobby[k], i);
  42.             else
  43.                 hobby[k] = i;
  44.         }
  45.     }
  46.    
  47.     int cnt[1010] = {0};
  48.     for (int i = 1; i <= n; i++)
  49.         cnt[find_root(i)]++;

  50.     sort(cnt, cnt + 1010, cmp);

  51.     int k = 0;
  52.     while (cnt[k])
  53.         k++;

  54.     printf("%d\n", k);
  55.     for (int i = 0; i < k; i++)
  56.     {
  57.         printf("%d", cnt[i]);
  58.         if (i < k - 1)  putchar(' ');
  59.     }

  60.     return 0;
  61. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-3 13:13

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表