P2024 [NOI2001]食物链(并查集+思维)

在这里插入图片描述在这里插入图片描述根据我们开三个集合:X,Y,Z.
这三个集合的满足:X吃Y吃Z吃X,也就是下图
在这里插入图片描述
也就是开三倍长度的并查集,X:1-n,Y:n+1-2n,Z:2n+1-3*n

对于a,b两个元素,如果是同类那么我们union(a,b),同时知道被他们吃的元素a+n,b+n也是同类,所以union(a+n,b+n)
同时知道被a+n,b+n吃的元素也是同类,所以union(a+2n,b+2n)(同类吃的元素也是同类,能吃同类的元素也是同类)

如果 a 吃 b 那么 a吃的元素和b是同类 也就是 union(a+n,b) , 吃b的元素和a也是同类 也就是union(b+2n,a)
吃a的元素和b吃的元素是同类 也就是 union(a+2
n,b+n)

AC代码

#include <iostream>
#include <cstring>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include<queue>
#include<math.h>
using namespace std;

// 初始化并查集
#define N 200005

int father[N];
void init() {
	for (int i = 0; i < N; i++)
		father[i] = i;
}


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

void un(int x, int y) {
	x = getfather(x);
	y = getfather(y);
	if (x != y)
		father[x] = y;
}



int main()
{
	int n, k;
	scanf("%d %d", &n, &k);
	init();
	int ans = 0;
	while (k--)
	{
		int m, x, y;
		scanf("%d %d %d", &m, &x, &y);
		if (x > n || y > n)
		{
			ans++;
			continue;
		}
		if (m == 1)
		{
			if (getfather(x) == getfather(y + n) || getfather(x) == getfather(y + 2 * n))
			{
				ans++;
			}
			else
			{
				un(x, y);
				un(x + n, y + n);
				un(x + 2 * n, y + 2 * n);
			}
		}
		else
		{
			if (getfather(x) == getfather(y) || getfather(x) == getfather(y + n))
			{
				ans++;
			}
			else
			{
				un(x, y + 2*n);
				un(x + n, y);
				un(x + 2 * n, y + n);
			}
		}
	}
	cout << ans << endl;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shihao Weng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值