第一次接触到并查集+分类的形式, 方法是**** 记录节点 x 和祖先的相对关系 **** 来表示集合
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include <algorithm>
#define ll long long
#define eps 1e-8
#define ms(x,y) (memset(x,y,sizeof(x)))
#define fr(i,x,y) for(int i=x;i<=y;i++)
using namespace std;
const int maxn=5e4+10;
int fa[maxn],ra[maxn];
void unset(int n)
{
fr(i,1,n)
fa[i]=i;
ms(ra,0);
}
int unfind(int x)
{
if(x!=fa[x])
{
int fx=unfind(fa[x]);
ra[x]=(ra[x]+ra[fa[x]])%3;
fa[x]=fx;
}
return fa[x];
}
bool un(int x,int y,int type)
{
int fx,fy;
fx=unfind(x);
fy=unfind(y);
if(fx==fy)
{
if((ra[y]-ra[x]+3)%3!=type)return 1;
else return 0;
}
fa[fy]=fx;
ra[fy]=(ra[x]-ra[y]+type+3)%3;
return 0;
}
int main()
{
int n,k;
scanf("%d%d",&n,&k);
unset(n);
int ans=0;
fr(i,1,k)
{
int d,x,y;
scanf("%d%d%d",&d,&x,&y);
if(x>n||y>n||(x==y&&d==2))
ans++;
else if(un(x,y,d-1))
ans++;
}
cout<<ans<<endl;
}