【PAT甲级】1107 Social Clusters (30 分)

一、题目分析

1. 翻译

register on:注册
cluster:集群

2. 分析

1)相同爱好的人为一个集群,原来我的错误理解:
请添加图片描述
正确的应该是:
请添加图片描述
因此想到用并查集,每个爱好的第一个人为这个集合的“祖宗”。
2)根据《算法笔记》中所说,是否进行路径压缩都可以。
3)注意ifwhile的使用,最近总是搞混。

二、代码解析

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <cctype>
#include <unordered_map>
#include <stack>
#include <queue>
using namespace std;
const int N=1010;//注意加const
int cluster[N]= {0};
int isRoot[N]= {0};
int father[N];

void init(int n) {
	for(int i=1; i<=n; i++) {
		father[i]=i;
	}
}
int findfather(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;
}
void _union(int a,int b) {
	int fa=findfather(a);
	int fb=findfather(b);
	if(fa!=fb) {//是if!不是while!
		father[fa]=fb;
	}
}
bool cmp(int a,int b) {
	return 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(cluster[h]==0) { //h爱好的第一个人
				cluster[h]=i;
			}
			_union(i,findfather(cluster[h]));
		}
	}
	for(int i=1; i<=n; i++) {
		isRoot[findfather(i)]++;
	}
	sort(isRoot+1,isRoot+n+1,cmp);
	int sum=0;
	for(int i=1; i<=n; i++) {
		if(isRoot[i]!=0) sum++;
	}
	cout<<sum<<endl;
	for(int i=1; i<=sum; i++) {
		cout<<isRoot[i];
		if(i!=sum) cout<<" ";
	}
	return 0;
}

三、我的疑问

如果喜欢我的博客,欢迎点赞、评论、收藏~~谢谢
( * ^ ▽ ^ * ) ~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值