蓝桥杯:历届试题 合根植物(并查集 + 索引思想)

题目:
https://blog.csdn.net/weixin_40163242/article/details/88397162

还是刚刚那道题,这次用并查集做就成功AC了。其实用并查集做完才发现,其实比广搜做还要简单啊!

这题简直就是裸的并查集了,然后这题还有一个索引的思想注意一下。在最后我将所有的boss结点的tag值置为1,然后我再遍历一遍tag数组,看哪些值为1,哪些就是boss结点了,那么问题的解实际上是等于boss结点的个数的。

AC代码:

#include<iostream>
using namespace std;

const int maxn = 1000005;
int m, n, k;
int tag[maxn];
int parent[maxn];

//-------------------并查集----------------------
void init()
{
	for(int i = 1;i <= n * m;i++)
		parent[i] = i;
}
 
int getBoss(int x)
{
	if(x == parent[x])
		return x;
	return getBoss(parent[x]);
}

int merge(int x, int y)
{
	int boss_x = getBoss(x);
	int boss_y = getBoss(y);			//这里之前复制的时候getBoss(x)。。。找错找了半天,粗心啊!! 
	parent[boss_x] = boss_y;
}

/*
judge函数本题可要可不要 
bool judge(int x, int y)
{
	int boss_x = getBoss(x);
	int boss_y = getBoss(x);
	return boss_x == boss_y;
}
*/
//------------------------------

int main()
{
	cin >> m >> n >> k;
	int ans = 0;
	init();						//初始化parent数组 
	for(int i = 1;i <= k;i++)
	{
		int a, b;
		cin >> a >> b;			//a与b存在合根关系 
		merge(a, b);			//那么我就让a与b merge起来
	}
	//运用索引思想,找出boss结点的个数,boss结点的个数等于关系数
	for(int i = 1;i <= n * m;i++)
	{
		tag[getBoss(i)] = 1;		//将boss结点的tag值标记为1,便于索引 
	} 
	//看tag值是否为1,就可以知道是否为boss结点了,而且也不会重复,索引思想!
	for(int i = 1;i <= n * m;i++)
	{
		if(tag[i] == 1)
			ans++;
	} 
	cout << ans << endl;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值