P5937. Parity Game

考点

  • 边带权并查集

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <bits/stdc++.h>
using namespace std;
const int LEN = 1e5 + 50;
int n, m, cnt, fa[LEN], val[LEN], discrete[LEN];

struct node {
int x_, y_, w_;
} arr[LEN];

int find(int x) {
if (fa[x] == x) return x;
int anc = fa[x];
fa[x] = find(fa[x]);
val[x] ^= val[anc];
return fa[x];
}

void join(int x, int y, int w) {
int a = find(x), b = find(y);
val[a] = w ^ val[y] ^ val[x];
fa[a] = b;
}

void init() {
// 离散化开始
sort(discrete + 1, discrete + 1 + cnt);
cnt = unique(discrete + 1, discrete + 1 + cnt) - (discrete + 1);
for (int i = 1; i <= m; ++i) {
arr[i].x_ =
lower_bound(discrete + 1, discrete + 1 + cnt, arr[i].x_) - discrete;
arr[i].y_ =
lower_bound(discrete + 1, discrete + 1 + cnt, arr[i].y_) - discrete;
}
// 离散化结束
for (int i = 0; i <= cnt; ++i) fa[i] = i;
}

void work() {
int x, y, w;
for (int i = 1; i <= m; ++i) {
x = arr[i].x_, y = arr[i].y_, w = arr[i].w_;
--x;
if (find(x) != find(y)) {
join(x, y, w);
} else {
if (val[x] ^ val[y] != w) {
cout << i - 1 << endl;
return;
}
}
}
cout << m << endl;
}

int main() {
string str;
cin >> n >> m;
for (int i = 1; i <= m; ++i) {
cin >> arr[i].x_ >> arr[i].y_ >> str;
arr[i].w_ = str[0] == 'e' ? 0 : 1;
discrete[++cnt] = arr[i].x_, discrete[++cnt] = arr[i].y_;
}
init(), work();
return 0;
}

思路

数据范围高达1e9,所以先需要离散化

路径压缩

先作图,发现结点之间的边权是可以传递的,可以进行路径压缩:

令偶数边权为0,奇数边权为1,可以发现以下规律:

x(x走到y步数的奇偶性) y(y走到z步数的奇偶性) z(x走到z步数的奇偶性) 备注
0 0 0 偶+偶=偶
0 1 1 偶+奇=奇
1 0 1 奇+偶=奇
1 1 0 奇+奇=偶

val[x] 为x走到当前祖先的所需步数,直接用异或即可:

1
新val[x] = 旧val[x] ^ 新val[父结点]

合并

根据上述推断,显然有x到y的步数 + y到祖先b的步数 = x到祖先b的步数

就可以得到祖先a到祖先b的步数 = x到y的步数 + y到祖先b的步数 - x到祖先a的步数