P2024 食物链
给出若干组食物链关系,判断某些关系是否成立(规定捕食关系为: 吃 , 吃 ,则 吃 )
前置知识点
扩展域并查集
关键
我们设 代表 , 代表
那么我们就可以按照普通并查集的方式,将符合上述性质的与 所在的集合合并即可归类。
总结
生动的理解起来,同样是有多元的关系维度,这种操作我们似乎是可以在分层图中体会到类似的思想,但回归集合处理的本质:
- 将 作为某个特定关系的代表元素,便于直接检索该集合并对其进行合并或查询操作
#include<bits/stdc++.h>
#define ll long long
#define debug(x) cout<<x<<' ';
using namespace std;
const int N=1e6+10;
/*
x+n:代表其捕食对象
x+2n:代表其天敌
*/
int n,T,fa[N];
int find(int x){
return fa[x]==x?x:fa[x]=find(fa[x]);
}
void unset(int x,int y){//这个题其实对你父节点就没有讲究
fa[find(y)]=find(x);
}
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>T;
for(int i=1;i<=3*n;i++) fa[i]=i;
int ans=0;
while(T--){
int x,y,op;cin>>op>>x>>y;
//显然矛盾
if(x>n||y>n){ ans++; continue; }
if(op==1){
//如果x反而被y吃
if(find(x)==find(y+n)||find(x)==find(y+2*n)){ ans++; continue; }
unset(x,y);
unset(x+n,y+n);
unset(x+2*n,y+2*n);
}
if(op==2){
//如果在一类
if(find(x)==find(y)||find(x)==find(y+n)){ ans++; continue; }
unset(x+n,y);
unset(x,y+2*n);
unset(x+2*n,y+n);
}
}
cout<<ans;
return 0;
}