任意两个点的关系 可以用0,1,2 三个数表示
C++ 代码
#include<numeric>
#include<algorithm>
#include<iostream>
using namespace std;
int d[50008], fa[50008];
int father(int x){
if(x == fa[x])
return x;
int root = father(fa[x]);
d[x] += d[fa[x]];
return fa[x] = root;
}
int main(){
int n, k, type, x, y, cnt = 0, fx, fy;
cin >> n >> k;
iota(fa, fa + n + 2, 0);
for(int i = 0; i < k; ++i){
cin >> type >> x >> y;
if(x > n || y > n){
cnt ++;
continue;
}
if(type == 1){
// A吃B B吃C 这样d[A] = 0, d[B] = 1, d[C] = 2 每个点与它所在的根的关系 就是0,1,2三个数 所以下面的都模3
if(father(x) == father(y) && d[x] % 3 != d[y] % 3)
cnt++;
else{
fx = father(x); fy = father(y);
d[fx] = (d[y] - d[x]) % 3;// 画图模拟可能更好理解
if(d[fx] < 0){
d[fx] = 3 + d[fx];
}
fa[fx] = fy;
}
}
else{
if(x == y || (father(x) == father(y) && (d[x] % 3) != (1 + d[y]) % 3))
cnt++;
else{
fx = father(x); fy = father(y);
d[fx] = (d[y] - (d[x] - 1)) % 3;
if(d[fx] < 0){
d[fx] = 3 + d[fx];
}
fa[fx] = fy;
}
}
}
cout << cnt << endl;
return 0;
}