1107 Social Clusters

25 篇文章 0 订阅
11 篇文章 0 订阅
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后面加了; 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值