题意:
中文不解释
分析:
每个节点包括两部分,关系域跟节点域,节点域更新跟普通并查集一样,关系域借助向量进行更新。
讲解的很好的博客:https://blog.csdn.net/niushuai666/article/details/6981689
#include<cstdio>
using namespace std;
const int maxn=5e4+10;
struct Node{
int pre;
int relation; // p[x].pre与x的关系 0 同类 1 x->y 2 y->x
}p[maxn];
int find(int x){
if(p[x].pre==x) return x;
int tmp=p[x].pre;
p[x].pre=find(tmp);
p[x].relation=(p[x].relation+p[tmp].relation)%3;
return p[x].pre;
}
int main(){
int n,k;
int op,a,b;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++){
p[i].pre=i;
p[i].relation=0;
}
int ans=0;
while(k--){
scanf("%d%d%d",&op,&a,&b);
if(a>n||b>n){
ans++;
continue;
}
if(op==2&&a==b){
ans++;
continue;
}
int root1=find(a);
int root2=find(b);
if(root1!=root2){
p[root2].pre=root1;
p[root2].relation=(p[a].relation+op-1-p[b].relation+3)%3;
}else{
if(op==1&&(p[a].relation!=p[b].relation)){
ans++;
continue;
}else if(op==2&&(-p[a].relation+p[b].relation+3)%3!=op-1){
ans++;
continue;
}
}
}
printf("%d\n",ans);
return 0;
}