【PTA】7-11 社交集群 (Java)

当你在社交网络平台注册时,一般总是被要求填写你的个人兴趣爱好,以便找到具有相同兴趣爱好的潜在的朋友。一个“社交集群”是指部分兴趣爱好相同的人的集合。你需要找出所有的社交集群。

输入格式:

输入在第一行给出一个正整数 N(≤1000),为社交网络平台注册的所有用户的人数。于是这些人从 1 到 N 编号。随后 N 行,每行按以下格式给出一个人的兴趣爱好列表:

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

其中Ki​(>0)是兴趣爱好的个数,hi​[j]是第j个兴趣爱好的编号,为区间 [1, 1000] 内的整数。

输出格式:

首先在一行中输出不同的社交集群的个数。随后第二行按非增序输出每个集群中的人数。数字间以一个空格分隔,行末不得有多余空格。

输入样例:

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

输出样例:

3
4 3 1

还是用并查集

import java.util.Arrays;
import java.util.Scanner;
public class Main {
    static int n;
    static int[] arr = new int[1005];
    static int[] count = new int[1005];
    static int[] fa = new int[1005];
    static int find(int x){
        if(fa[x]==x)
            return x;
        else{
            fa[x]=find(fa[x]);
            return fa[x];
        }

    }
    static void union(int x, int y){
        int t1=find(x);
        int t2=find(y);
        if(t1 != t2) fa[t1]=t2;
    }
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        n = s.nextInt();
        s.nextLine();
        for (int i = 1; i <= 1000; i++) {
            fa[i] = i;
        }
        for (int i = 1; i <= n; i++) {
            String[] ss = s.nextLine().replace(":","").split(" ");
            int m = Integer.parseInt(ss[0]);
            arr[i] = Integer.parseInt(ss[1]);
            for (int j = 1; j <= m - 1; j++) {
                int x = Integer.parseInt(ss[j]);
                int y = Integer.parseInt(ss[j+1]);
                union(x,y);
            }
        }
        for (int i = 1; i <= n; i++) {
            int p = find(arr[i]);
            count[p]++;
        }
        Arrays.sort(count);
        int c = 0;
        for (int i = 1; i < 1005; i++) {
            if (count[i]!=0) c++;
        }
        System.out.println(c);
        System.out.print(count[count.length-1]);
        for (int i = 2; i <= c; i++) {
            System.out.print(" " + count[count.length-i]);
        }
        s.close();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值