题目:
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;
}