2021.01.21
**并查集**,找爹(bushi)
emmm,没什么好说的,列个模板吧。
贴个题
代码
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cstdio>
using namespace std;
const int MAX = 50010;
int ran[MAX], f[MAX];
int N, K;
void init() {
for (int i = 0; i <= N; i++)
f[i] = i, ran[i] = 0;
}
int root(int x) {
if (x == f[x])
return x;
int temp = f[x];
f[x] = root(f[x]);
ran[x] = (ran[x] + ran[temp])%3;
return f[x];
}
void connect(int a, int b, int type) {
int fa = root(a);
int fb = root(b);
if (fa == fb)
return;
f[fa] = fb;
ran[fa] = (type+ran[b]-ran[a]+3)%3;
}
bool check(int a, int b, int type) {
if (a > N || b > N)
return false;
if (type == 1 && a == b)
return false;
if (root(a) == root(b))
return (ran[a]-ran[b]+3)%3 == type;
else
return true;
}
int main() {
int ans = 0;
scanf("%d %d", &N, &K);
init();
while (K--) {
int D, X, Y;
scanf("%d %d %d", &D, &X, &Y);
D--;
if (check(X, Y, D))
connect(X, Y, D);
else
ans++;
}
printf("%d\n", ans);
}