三角关系并查集
题目luogu P2024 [NOI2001] 食物链
各个并查集中不一定是同一类了,有了权值
ACcode
//https://www.luogu.com.cn/problem/P2024
#include<bits/stdc++.h>
#define N 50010
using namespace std;
typedef long long ll;
void setio(string);
int n,k,f[N],cost[N]; //cost指向父亲的边的属性(0~3)0同类 1吃 2被吃
int ans=0;
int gf(int x){//找祖先并路径压缩
if(f[x]==x)return x;
int tmp=gf(f[x]);
cost[x]=(cost[x]+cost[f[x]])%3;
f[x]=f[f[x]];
return f[x];
}
int main(){
setio("");
cin>>n>>k;
for(int i=1;i<=n;i++){//并查集init
f[i]=i;
cost[i]=0;
}
for(int i=1,op,x,y;i<=k;i++){
cin>>op>>x>>y;
if(x==y && op==2 || x>n || y>n){//必假
ans++;
continue;
}
int xx=gf(x),yy=gf(y);
if(xx==yy){//判断是否为真(双路cost同余)
if((op==1 && cost[x]!=cost[y]) || (op==2 && (1+cost[y]-cost[x]+3)%3!=0))ans++;
}else{//必定为真,直接操作
cost[xx]=(3-cost[x])%3;
cost[yy]=(3-cost[y])%3;
f[xx]=x;
f[yy]=y;
f[x]=f[y]=y;
if(op==1)cost[x]=0;//同类
else cost[x]=1;//吃
cost[y]=0;
}
}
cout<<ans<<endl;
return 0;
}
void setio(string name){
ios_base::sync_with_stdio(0);
cin.tie(0);
if(name!=""){
freopen((name+".in").c_str(),"r",stdin);
freopen((name+".out").c_str(),"w",stdout);
}
}
作者:ShaoJia,欢迎分享本文,转载时敬请注明原文来源链接。

浙公网安备 33010602011771号