方法1:用带边权的并查集
- 写法1
#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 20010;
int n, m;
int p[N], d[N];
unordered_map<int, int> S;
int get(int x) {
if (S.count(x) == 0) S[x] = ++n;
return S[x];
}
int find(int x) {
if (p[x] != x) {
int root = find(p[x]);
d[x] = d[x] ^ d[p[x]];
p[x] = root;
}
return p[x];
}
int main() {
cin >> n >> m;
n = 0;
for (int i = 0; i < N; i++) p[i] = i;
int res = m;
for (int i = 1; i <= m; i++) {
int a, b;
string type;
cin >> a >> b >> type;
a = get(a - 1), b = get(b);
int t = 0;
if (type == "odd") t = 1;
int pa = find(a), pb = find(b);
if (pa == pb) { // 说明a和b在同一个集合中
if ((d[a] ^ d[b]) != t) {
res = i - 1;
break;
}
} else {
p[pa] = pb;
d[pa] = d[a] ^ d[b] ^ t;
}
}
cout << res << endl;
return 0;
}
- 写法2
也可以采用下面的写法(d[x]存储x到父节点的距离,类似于食物链的做法):
#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 20010;
int n, m;
int p[N], d[N];
unordered_map<int, int> S;
int get(int x) {
if (S.count(x) == 0) S[x] = ++n;
return S[x];
}
int find(int x) {
if (p[x] != x) {
int root = find(p[x]);
d[x] += d[p[x]]; // 可能会导致溢出
p[x] = root;
}
return p[x];
}
int main() {
cin >> n >> m;
n = 0;
for (int i = 0; i < N; i++) p[i] = i;
int res = m;
for (int i = 1; i <= m; i++) {
int a, b;
string type;
cin >> a >> b >> type;
a = get(a - 1), b = get(b);
int t = 0;
if (type == "odd") t = 1;
int pa = find(a), pb = find(b);
if (pa == pb) { // 说明a和b在同一个集合中
if (((d[a] + d[b]) % 2 + 2) % 2 != t) { // 必须保证余数为负,也可以处理
res = i - 1;
break;
}
} else {
p[pa] = pb;
d[pa] = d[a] + d[b] + t;
}
}
cout << res << endl;
return 0;
}
方法2:带扩展域的并查集
#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 40010, Base = N / 2;
int n, m;
int p[N], d[N];
unordered_map<int, int> S;
int get(int x) {
if (S.count(x) == 0) S[x] = ++n;
return S[x];
}
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main() {
cin >> n >> m;
n = 0;
for (int i = 0; i < N; i++) p[i] = i;
int res = m;
for (int i = 1; i <= m; i++) {
int a, b;
string type;
cin >> a >> b >> type;
a = get(a - 1), b = get(b);
if (type == "even") {
if (find(a + Base) == find(b)) {
// 此时题目输入为a,b是同类,但是发现a,b是异类,矛盾
res = i - 1;
break;
}
p[find(a)] = find(b);
p[find(a + Base)] = find(b + Base);
} else {
if (find(a) == find(b)) {
// 此时题目输入为a,b是异类,但是发现a,b是同类,矛盾
res = i - 1;
break;
}
p[find(a + Base)] = p[find(b)];
p[find(a)] = p[find(b + Base)];
}
}
cout << res << endl;
return 0;
}