The Suspects POJ - 1611【并查集】

该博客详细解析了编程竞赛题目The Suspects POJ-1611的解决方案,使用了并查集作为主要算法。通过并查集模板,博主展示了如何初始化、查找和合并集合,并最终输出指定节点所在集合的元素数量。代码中包含了关键的find和unite函数,以及问题求解过程。
摘要由CSDN通过智能技术生成

The Suspects POJ - 1611

题目

思路:并查集模板题,开一个cnt数组维护集合中点的数量,最后输出0号点所在集合中点的数量就可以了

具体代码如下

#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;

const int N = 30010;

int n, m;
int p[N], cnt[N];
int group[N];

int find(int x){
	if(p[x] != x) p[x] = find(p[x]);
	return p[x];
}

void unite(int x, int y){
	x = find(x), y = find(y);
	if(x == y) return;
	p[x] = y;
	cnt[y] += cnt[x];
}

int main(){
	
	while(~scanf("%d%d", &n, &m)){
		if(n == 0 && m == 0) break;
		
		for(int i=0; i<n; ++i){
			p[i] = i;
			cnt[i] = 1;
		}
		
		while(m--){
			int n2;
			scanf("%d", &n2);
			for(int i=0; i<n2; ++i) scanf("%d", &group[i]);
			for(int i=1; i<n2; ++i){
				unite(group[i-1], group[i]);
			}
		}
		printf("%d\n", cnt[find(0)]);
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值