这个是挑战程序那本书上的代码,自己实现了一下。
#include <iostream>
#include <stdio.h>
using namespace std;
//const int MAX_N = 100000 + 7;
int N, K;
//int T[MAX_N], X[MAX_N], Y[MAX_N];
int f[3 * 50000 + 7];
int find (int x) {
if (x != f[x])
f[x] = find(f[x]);
return f[x];
}
void unite (int x, int y) {
int fx = find (x);
int fy = find (y);
if (fx != fy)
f[f[x]] = fy;
}
bool same (int x, int y) {
return find(x) == find(y);
}
void init (int n) {
for (int i = 1; i <= n; i++)
f[i] = i;
}
void solve () {
init (N * 3);
int ans = 0;
for (int i = 0; i < K; ++i) {
int t, x, y;
scanf ("%d%d%d", &t, &x, &y);
// cin >> t >> x >> y;
x --; y --;
//int t = T[i]; // 类型
//int x = X[i] - 1, y = Y[i] - 1; //
if (x < 0 || N <= x || y < 0 || N <= y) {
ans ++;
continue;
}
if (t == 1) {
if (same (x, y + N) || same (x, y + 2 * N)) {
ans ++;
} else {
unite (x, y);
unite (x + N, y + N);
unite (x + 2 * N, y + 2 * N);
}
} else {
if (same (x, y) || same (x, y + 2 * N)) {
ans ++;
} else {
unite (x, y + N);
unite (x + N, y + 2 * N);
unite (x + 2 * N, y);
}
}
}
cout << ans << endl;
}
int main () {
cin >> N >> K;
// for (int i = 0; i < K; ++i) {
// cin >> T[i] >> X[i] >> Y[i];
// }
solve ();
return 0;
}