while(x != father[x]){
x = father[x];
}
这个有点绕,
这样就能看出,从3找父亲, 就是 x = father[x]的过程
for (int i = 1; i <= n; i++) {
scanf("%d", &k);
for (int j = 0; j < k; j++) {
scanf("%d", &h);
if (course[h] == 0); {
course[h] = i;//i喜欢活动h
}
Union(i, findFather(course[h]));//i喜欢h,1喜欢h1, 则1 是h1的孩子
}
}
这段代码有点难理解
其实是这样的
8
3: 2 7 10
1: 4
2: 5 3
1: 4
1: 3
1: 4
4: 6 8 1 5
1: 4
course[2, 7, 10] = i,如果后面有course[2,7,10]出现,则出现的序号in为i的孩子
这是看case能生成三个系
注意数字均为序号i
2->4->6->8
3->5->7
1
即三棵树,这样差不多这道题就能明白了
#include <cstdio>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <cstring>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <ctype.h>
using namespace std;
const int N = 1010;
int father[N];//存放父亲节点
int isroot[N] = { 0 };//记录每个节点是否作为某个集合的根结点
int course[N] = { 0 };
void init(int n) {
for (int i = 1; i <= n; i++) {
father[i] = i;
}
}
bool cmp(int a, int b) {
return a > b;
}
int findFather(int x) {
int a = x;
while (x != father[x]) {
x = father[x];//这个有点难想
}
//此时x是根结点,
while (a != father[a]) {
int z = a;
a = father[a];
father[z] = x;//a到根路径中 所有节点的father都为1
}
return x;//返回根结点
}
void Union(int a, int b) {//合并a和b的集合
int faA = findFather(a);
int faB = findFather(b);
if (faA != faB) {
//如果a和b不是在同一棵树,
father[faA] = faB;
//A树长在了B树上面
}
}
int main() {
int n, k, h;
scanf("%d", &n);
init(n);
for (int i = 1; i <= n; i++) {
scanf("%d:", &k);
for (int j = 0; j < k; j++) {
scanf("%d", &h);
if (course[h] == 0){
course[h] = i;//i喜欢活动h
}
Union(i, findFather(course[h]));//i喜欢h,1喜欢h1, 则1 是h1的孩子
}
}
for (int i = 1; i <= n; i++) {
isroot[findFather(i)]++;//统计成员数,每个数都有一个根
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (isroot[i] != 0) {
ans++;
}
}
printf("%d\n", ans);
sort(isroot + 1, isroot + n + 1, cmp);
for (int i = 1; i <= ans; i++) {
printf("%d", isroot[i]);
if (i != ans) printf(" ");
}
return 0;
}
一开始数据总数不对,没想到if后面加了;