L3-003 社交集群 (30 分)
链接:
社交集群
当你在社交网络平台注册时,一般总是被要求填写你的个人兴趣爱好,以便找到具有相同兴趣爱好的潜在的朋友。一个“社交集群”是指部分兴趣爱好相同的人的集合。你需要找出所有的社交集群。
输入格式:
输入在第一行给出一个正整数 N(≤1000),为社交网络平台注册的所有用户的人数。于是这些人从 1 到 N 编号。随后 N 行,每行按以下格式给出一个人的兴趣爱好列表:
输出格式:
首先在一行中输出不同的社交集群的个数。随后第二行按非增序输出每个集群中的人数。数字间以一个空格分隔,行末不得有多余空格。
输入样例:
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
package highLadder;
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* @author hang
* @create 2022-03-19 12:59
*/
public class L3003 {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static int[] number = new int[1010];//判断兴趣圈相同的人数
static int[] arr = new int[1010];// 并查集数组
static int find(int x) {
int y = arr[x];
while(x != arr[x]) {
x = arr[x];
}
return arr[y] = x;
}
static void union(int x, int y) {
int i = find(x);
int j = find(y);
if (i != j ) {
arr[i] = j;
number[j] += number[i];
}
}
public static void main(String[] args) throws IOException {
int n = nextInt();
for (int i = 0; i < 1010; i ++) {
arr[i] = i;
}
for (int i = 0; i < n; i ++) {
String a = next();
int m = Integer.parseInt(a.charAt(0) + "");
int b = nextInt();
number[b] ++;
if (b != find(b)) {
number[find(b)] ++;
}
for (int j = 1; j < m; j ++) {
int c = nextInt();
union(b,c);
}
}
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < 1010; i ++) {
if (arr[i] == i && number[i] > 0) {
arrayList.add(number[i] );
}
}
arrayList.sort((a,b) -> {return b - a;});
System.out.println(arrayList.size());
int t = 0;
for (int i : arrayList) {
if (t == 0) {
System.out.print(i);
t = 1;
} else {
System.out.print(" " + i);
}
}
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDoule() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
思路:并查集,将同一个兴趣圈的兴趣进行并查集,number数组记录人数