POJ1733 Parity game 扩展域并查集

题目链接

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

分析

与程序自动分析那道题不同, a ≠ b a \neq b a=b b ≠ c b \neq c b=c,并不意味着 a = c a = c a=c

而本题和关押罪犯类似, a a a b b b 不在一间牢房, b b b c c c 不在一间牢房,则 a a a c c c 必在一间牢房;

可以额外开一倍节点来记录不等关系,分析与带权并查集做法类似。

AC代码

#include <cstdio>
#include <algorithm>

using namespace std;

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 = 5e3 + 5;

struct Query {
	int l, r, ans;
} q[maxn];

int a[2 * maxn], f[4 * maxn];

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

inline void merge(int x, int y) {
	x = find(x), y = find(y);
	f[x] = y;
}

int main() {
	int n = read(), m = read();
	char oe[5];
	for (int i = 1; i <= m; ++i) {
		q[i].l = a[i] = read() - 1, q[i].r = a[i + m] = read();
		scanf("%s", oe);
		q[i].ans = oe[0] == 'o' ? 1 : 0;
	}
	sort(a + 1, a + 2 * m + 1);
	n = unique(a + 1, a + 2 * m + 1) - a - 1;
	for (int i = 1; i <= m; ++i) {
		q[i].l = lower_bound(a + 1, a + n + 1, q[i].l) - a;
		q[i].r = lower_bound(a + 1, a + n + 1, q[i].r) - a;
	}
	for (int i = 1; i <= 2 * n; ++i) f[i] = i;
	for (int i = 1; i <= m; ++i) {
		int x = q[i].l, y = q[i].r;
		if (q[i].ans) {
			if (find(x) == find(y)) {
				printf("%d", i - 1);
				return 0;
			}
			merge(x, y + n), merge(x + n, y);
		} else {
			if (find(x) == find(y + n)) {
				printf("%d", i - 1);
				return 0;
			}
			merge(x, y), merge(x + n, y + n);
		}
	}
	printf("%d", m);
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值