import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
static int father[] = new int[1010];
static int course[] = new int[1010];
static int isRoot[] = new int[1010];//标记根节点,同时用来求集合内的个数
//如果我这里改成了Integer数组,则会提示空指针异常
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
init(n);//先初始化
sc.nextLine();
for(int i = 1; i <= n; i++){
String[] s = sc.nextLine().split(" ");
int k = s[0].charAt(0) - '0';
for(int j = 1; j <= k; j++){
int cour = Integer.parseInt(s[j]);
if(course[cour] == 0){//表示为第一次
course[cour] = i;//cour用来做数组下标
}
uinion(i, findFa(course[cour]));//此处进行集合的合并
}
}
for(int i = 1; i <= n; i++){
isRoot[findFa(i)]++;//遍历每一个点
}
int cnt = 0;
for(int i = 1; i <= n; i++){
if(isRoot[i] != 0) cnt++;
}
System.out.println(cnt);//此即为集合的个数
Arrays.sort(isRoot);
Integer[] copy = new Integer[1010];
for(int i = 0; i < 1010; i++){
copy[i] = isRoot[i];
}
Arrays.sort(copy, new Comparator<Integer>() {//只能一个一个变化成Integer数组
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
for(int i = 0; i< cnt; i++){
System.out.print(copy[i]);
if(i < cnt - 1) System.out.print(" ");
}
/*for(int i = 1; i<= cnt; i++){//Arrays.sort()不支持int数组从大到小
System.out.print(isRoot[1010 - i]);
if(i < cnt) System.out.print(" ");
}*/
}
static void init(int n){
for(int i = 1; i <= n; i++){
father[i] = i;
}
}
static int findFa(int x){
int a= x;
while(x != father[x]){
x = father[x];
}
//路径压缩
while(a != father[a]){
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
static void uinion(int a, int b){
int fa = findFa(a);
int fb = findFa(b);
if(fa != fb){
father[fa] = fb;
}
}
}
并查集应用PAT1107
最新推荐文章于 2022-08-08 09:59:24 发布