可以建立3*n的并查集,x,x+n,x+2*n分别代表一个食物圈。即若x和y属于一个类别的情况就是x和y连接,(x+n)和(y+n)连接,(x+2*n)和(y+2*n)连接;如果x吃y,那么x和(y+n)连接,(x+n)和(y+2*n)连接,(x+2*n)和y连接。依次连接即可
#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<set>
#include<bitset>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<utility>
#define INF 0x3f3f3f3f
#define inf 2*0x3f3f3f3f
#define llinf 1000000000000000000
#define pi acos(-1.0)
#define mod 1000000007
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lrt rt<<1
#define rrt rt<<1|1
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define mem(a,b) memset(a,b,sizeof(a))
#define lb(x) (x&-x)
#define gi(x) scanf("%d",&x)
#define gi2(x,y) scanf("%d%d",&x,&y)
#define gll(x) scanf("%lld",&x)
#define gll2(x,y) scanf("%lld%lld",&x,&y)
#define gc(x) scanf("%c",&x)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int>P;
/***********************************************/
int n,k,cnt=0,par[50005*3],ranks[50005*3],num,x,y;
void init(int n)
{
rep(i,0,n)par[i]=i,ranks[i]=0;
}
int finds(int x)
{
if(par[x]==x)return x;
return par[x]=finds(par[x]);
}
void unite(int x,int y)
{
x=finds(x),y=finds(y);
if(x==y)return ;
if(ranks[x]>ranks[y])par[y]=x;
else par[x]=y;
if(ranks[x]==ranks[y])ranks[y]++;
}
bool same(int x,int y)
{
return finds(x)==finds(y);
}
int main()
{
cin>>n>>k;
init(n*3);
rep(i,0,k)
{
gi(num);gi2(x,y);x--,y--;
if(x>=n||y>=n){cnt++;continue;}
if(num==1)
{
if(same(x,y+n)||same(x,y+2*n))cnt++;
else {unite(x,y),unite(x+n,y+n),unite(x+2*n,y+2*n);}
}
else
{
if(same(x,y)||same(x,y+2*n))cnt++;
else {unite(x,y+n),unite(x+n,y+2*n),unite(x+2*n,y);}
}
}
cout<<cnt;
return 0;
}