poj 2524 Ubiquitous Religions

本文详细介绍了并查集算法的基本概念及其应用,并提供了完整的代码实现。通过对并查集的初始化、查找、合并等操作的讲解,帮助读者理解如何解决特定类型的连通性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  没什么可说的,我自己写的都一次通过了.

   自己写的代码还要注意细节.

#include<stdio.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAX 50000
#define MAXN 1300000000
int father[MAX],son[MAX];
long long i;
void Uset(int n)
{
	for(i=1;i<=n;i++)
	{
		father[i]=i;
		son[i]=1;
	}
}
int find(int x)
{
	return (x == father[x] ? x : find(father[x]) );
}
bool Union(long long  x,long long y)//有问题啊
{
	long long root1=find(x);
	long long root2=find(y);
	if(root1 == root2)
		return false;
	else if(son[root1] >= son[root2])
	{
		father[root2]=root1;
		son[root1]+=son[root2];

	}
	else
	{
		father[root1]=root2;
		son[root2]+=son[root1];
	}
	return true;

}
int main()
{
//	freopen("1232.txt","r",stdin);
	long long n,m,a,b,count;
	int kcase=0;//?
	while(1)
	{
		scanf("%lld%lld",&n,&m);
		Uset(n);
		if(n==0 && m==0)
			break;
		count=0;
		while(m--)
		{
			scanf("%lld%lld",&a,&b);
//		Union(a,b);
			if(Union(a,b))
				++count;


		}
		kcase++;
		printf("Case %d: %lld\n",kcase,n-count);
//		printf("son[1]=%d\n",son[1]);
	}
	
	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值