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