题目链接
思路
$$ \begin{aligned}并查集经典入门题\end{aligned} $$
时间复杂度
$$ O(N \alpha (N)) $$
代码
#include <cstdio>
#include <vector>
using namespace std;
class DSU {
public:
vector<int> p, r;
void init(int n) {
p.resize(n + 10);
r.resize(n + 10);
for (int i = 0; i <= n; i++) {
p[i] = i;
r[i] = 0;
}
}
int find(int x) {
if (x == p[x]) {
return x;
} else {
return p[x] = find(p[x]);
}
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
if (r[x] < r[y]) {
p[x] = y;
} else {
p[y] = x;
if (r[x] == r[y]) {
r[x]++;
}
}
return true;
}
bool same(int x, int y) {
return find(x) == find(y);
}
};
int main() {
int n, k;
scanf("%d%d", &n, &k);// don't forget &
DSU dsu;
dsu.init(3 * n);
int ans = 0;
while (k--) {
int d, x, y;
scanf("%d%d%d", &d, &x, &y);// don't forget &
if (x > n || y > n) {
ans++;
continue;
}
if (d == 1) {
if (dsu.same(x, y + n) || dsu.same(x, y + 2 * n)) {
ans++;
} else {
dsu.unite(x, y);
dsu.unite(x + n, y + n);
dsu.unite(x + 2 * n, y + 2 * n);
}
} else {
if (x == y) {
ans++;
continue;
}
if (dsu.same(x, y) || dsu.same(x, y + 2 * n)) {
ans++;
} else {
dsu.unite(x, y + n);
dsu.unite(x + n, y + 2 * n);
dsu.unite(x + 2 * n, y);
}
}
}
printf("%d", ans);
return 0;
}