当你在社交网络平台注册时,一般总是被要求填写你的个人兴趣爱好,以便找到具有相同兴趣爱好的潜在的朋友。一个“社交集群”是指部分兴趣爱好相同的人的集合。你需要找出所有的社交集群。
输入格式:
输入在第一行给出一个正整数 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();
}
}