//涉及到集合,合并 使用并查集
https://www.acwing.com/problem/content/description/242/
#include<iostream>
using namespace std;
const int N=50000+10;
int f[N],d[N];
int n,k;
//x-->f[x]---->root
int find(int x){
if(x!=f[x]){
int u=find(f[x]);
d[x]+=d[f[x]];
f[x]=u;
}
return f[x];
}
int main(){
cin>>n>>k;
for(int i=1;i<=n;i++) f[i]=i;
int res=0;
while(k--){
int op,x,y;
cin>>op>>x>>y;
if(x>n||y>n) res++;
else{
if(op==1){
int px=find(x),py=find(y);
if(px==py && (d[x]-d[y])%3) res++;//如果是一个集合,可以确定关系,判断是不是一种
else if(px!=py ){ // 不是一个集合,不可以确定关系,加入
f[px]=py;
d[px]=d[y]-d[x];
}
}
else{
int px=find(x),py=find(y);
if(px==py && (d[x]-d[y]-1)%3) res++;
else if(px!=py){
f[px]=py;
d[px]=d[y]-d[x]+1;
}
;
}
}
}
cout<<res<<endl;
return 0;
}
posted on
浙公网安备 33010602011771号