题目链接:食物链
分析
把猎物,天敌都放在一个并查集中,
x
+
n
x+n
x+n表示天敌
x
+
2
n
x+2n
x+2n表示猎物
然后再去查找
上代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int n,k,ans;
int fa[150001];
int father(int x)
{
if(fa[x]==x) return x;
return fa[x]=father(fa[x]);
}
int main()
{
cin>>n>>k;
for(int i=1;i<=3*n;i++)
{
fa[i]=i;
}
while(k--)
{
int z,x,y;
cin>>z>>x>>y;
if(x>n||y>n)
{
ans++;
continue;
}
int fx=father(x),fy=father(y);
int dx=father(x+n),dy=father(y+n);
int lx=father(x+2*n),ly=father(y+2*n);
if(z==1)
{
if(dx==fy||dy==fx)
{
ans++;
continue;
}
fa[fy]=fx;
fa[dy]=dx;
fa[ly]=lx;
}
else
{
if(fx==fy||dx==fy)
{
ans++;
continue;
}
fa[fx]=dy;
fa[dx]=ly;
fa[lx]=fy;
}
}
cout<<ans;
return 0;
}