NOI2001 食物链 扩展域并查集

题目链接

http://poj.org/problem?id=1182

分析

由于吃与被吃关系构成了一个环,所以我们可以用扩展域并查集来维护关系;

对于每种动物,建三个节点分别保存自身,能吃的与会被吃的。

AC代码

#include <cstdio>

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

const int maxn = 5e4 + 5;

int f[3 * maxn];

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

inline void merge(int a, int b) {
	a = find(a), b = find(b);
	f[a] = b;
}

int main() {
	int n = read(), k = read(), cnt = 0;
	for (int i = 1; i <= 3 * n; ++i) f[i] = i;
	while (k--) {
		int d = read(), x = read(), y = read();
		if (x > n || y > n || (d == 2 && x == y)) ++cnt;
		else if (d == 1) {
			if (find(x) == find(y + n) || find(y) == find(x + n)) ++cnt;
			else merge(x, y), merge(x + n, y + n), merge(x + 2 * n, y + 2 * n);
		}
		else if (d == 2) {
			if (find(x) == find(y) || find(x) == find(y + n)) ++cnt;
			else merge(x, y + 2 * n), merge(x + n, y), merge(x + 2 * n, y + n);
		}
	}
	printf("%d", cnt);
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值