-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem0239.h
80 lines (71 loc) · 1.74 KB
/
Problem0239.h
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
// Created by Fengwei Zhang on 9/20/21.
//
#ifndef ACWINGSOLUTION_PROBLEM0239_H
#define ACWINGSOLUTION_PROBLEM0239_H
#include <iostream>
#include <unordered_map>
using namespace std;
class Problem0239 {
// https://www.acwing.com/solution/content/29308/
// 异或运算自己是自己的逆运算
private:
static const int N = 20010;
int parent[N], dist[N];
unordered_map<int, int> dataTable;
int pTop = 0;
int find_root(int x) {
auto u = x;
while (u != parent[u]) {
u = parent[u];
}
while (x != u) {
auto p = parent[x];
parent[x] = u;
x = p;
}
return u;
}
int getIdx(const int a) {
if (dataTable.count(a) == 0) {
dataTable[a] = pTop;
++pTop;
}
return dataTable[a];
}
bool merge_sets(const int a, const int b, const string &type) {
int t = 0;
if (type == "odd") {
t = 1;
}
auto pa = find_root(a);
auto pb = find_root(b);
if (pa == pb) {
return dist[a] ^ dist[b] == t;
}
parent[pa] = pb;
dist[pa] = dist[a] ^ dist[b] ^ t;
return true;
}
int main() {
for (int i = 0; i < N; ++i) {
parent[i] = i;
}
int n, m;
scanf("%d%d", &n, &m);
auto result = m;
int a, b;
string type;
for (int i = 1; i <= m; ++i) {
cin >> a >> b >> type;
a = a - 1;
if (!merge_sets(getIdx(a), getIdx(b), type)) {
result = i - 1;
break;
}
}
cout << result << endl;
return 0;
}
};
#endif //ACWINGSOLUTION_PROBLEM0239_H