三角关系并查集

题目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);
}
}
posted @   ShaoJia  阅读(51)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示