题目: POJ - 1733 Parity game (带权并查集)
题目大意:给出n代表这个字符串长度为n,然后给m条关系表示x -- y 这样的位置中1出现的次数的奇偶性。问这样的关系中,是否有出现前k条都是符合条件的, 而第k + 1产生了矛盾,有的输出k,没有的话输出m。
解题思路:这题重点弄明白一下两点:
1、这题的n非常的大,以题目所给的资源是不能开这样的数组的,然而这题的关系m比较小,说明别访问到的点的位置也比较有限,所以可以用map来代替数组,这样就不必要开这么大的数组。
2、这题给的是x -- y 之间1出现的奇偶次数,但是这样的话 1 -- 2 3 -4 这样的两个串该如何关联呢?我们只要让 4 关联到(3 - 1) = 2 就可以了 这样就可以将1 - 4 关联起来形成一串。
代码:
#include <stdio.h>
#include <map>
using namespace std;
int n, m;
map<int, int> f, c;
void init (int x) {
if (f.count(x))
return ;
f[x] = x;
c[x] = 0;
}
int getfather (int x) {
if (x != f[x]) {
int t = f[x];
f[x] = getfather (f[x]);
c[x] = (c[x] + c[t]) % 2;
}
return f[x];
}
int main () {
while ( scanf ("%d%d", &n, &m) != EOF ) {
char str[10];
int x, y, v, ans = m;
for (int i = 0; i < m; i++) {
scanf ("%d%d%s", &x, &y, str);
if (ans != m)
continue;
init (x - 1);
init (y);
if (str[0] == 'o')
v = 1;
else
v = 0;
int p = getfather (x - 1);
int q = getfather (y);
if (p != q) {
f[q] = p;
c[q] = (v + c[x - 1] + c[y] + 2) % 2;
// printf("!=");
} else if ((c[y] - c[x - 1] + 2) % 2 != v){
ans = i;
//printf ("=");
}
// printf ("%d %d %d\n", p, q, v);
// printf ("%d %d\n",f[q], c[q]);
}
printf ("%d\n", ans);
f.clear();
c.clear();
}
return 0;
}