【算法笔记】并查集:好朋友和1107 Social Clusters 测试点2问题

【好朋友】
设定初始化、查找父结点、合并三个方法,先初始化father数组,再针对朋友a、b,如果朋友a、b的父结点为同一个,即在同一个社交网络里,则不用合并a、b,否则将a、b合并到同一网络中。
最后循环所有结点,判断它们的父结点是否出现过,来计算所有组数。

#include<stdio.h>

const int maxn = 101;
int n, m;
int father[maxn];
bool isfather[maxn] = {false};

void Initf(){
	for(int i = 1; i <= n; i++){
		father[i] = i;
	}
}

int Findfather(int x){
	if(father[x] == x) {
		return x;
	}
	return Findfather(father[x]);		
	
}
	
void Union(int a, int b){
	int fathera = Findfather(a);
	int fatherb = Findfather(b);
	father[fathera] = fatherb;
}

int main(){
	scanf("%d %d", &n, &m);
	Initf();
	for(int i = 0; i < m; i++){
		int a, b;
		scanf("%d %d", &a, &b);
		if(Findfather(a) != Findfather(b)){
			Union(a, b);
		} 	
	}
	int count = 0;
	for(int i = 1; i <= n; i++){
		int f = Findfather(i);
		if(isfather[f] == false){
			count++;
			isfather[f] = true;
		}
	}
	printf("%d", count);
}

【1107 Social Clusters】
测试点2出现错误,原因是人的下标是从1开始的,因此结束时是N+1,sort排序时应该是sort(countfather, countfather + N + 1, cmp);

#include<stdio.h>
#include<algorithm>
using namespace std;

const int maxn = 1010;
int N;
int father[maxn];
int hobby[maxn] = {0};
bool isfather[maxn] = {false};
int countfather[maxn] = {0};

bool cmp(int a, int b){
	return a>b;
}
void Init(){
	for(int i = 1; i <= N; i++){
		father[i] = i;
	}	
}

int Findfather(int x){
	if(x == father[x]) return x;
	return Findfather(father[x]);
}

void Union(int a, int b){
	int fa = Findfather(a);
	int fb = Findfather(b);
	if(fa != fb){
		father[fa] = fb;
	}
}

int main(){
	scanf("%d", &N);
	Init();
	for(int i = 1; i <= N; i++){
		int k;
		scanf("%d", &k);
		getchar();
		getchar();
		for(int j = 0; j < k; j++){
			int h;
			scanf("%d", &h);
			if(hobby[h] == 0){
				hobby[h] = i;
			}
			Union(i, hobby[h]);
		}
	}
	int count = 0;
	for(int i = 1; i <= N; i++){
		int f = Findfather(i);
		if(isfather[f] == false){
			isfather[f] = true;
			count++;
		}
		countfather[f] += 1;
	}
	printf("%d\n", count);
	sort(countfather, countfather + N + 1, cmp);
	for(int i = 0; i < count; i++){
		printf("%d", countfather[i]);
		if(i < count - 1){
			printf(" ");
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值