跳到正文

个人记录

扩展域并查集

Listedzero约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年11月22日
收录
2026年8月26日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前

P2024 食物链

给出若干组食物链关系,判断某些关系是否成立(规定捕食关系为:AA 吃 BB,BB 吃 CC,则 CC 吃 AA)

前置知识点

扩展域并查集

关键

我们设 x+nx+n 代表 S1{x可以捕食的生物}S_1\{x 可以捕食的生物\}, x+2nx+2n 代表 S2{x的天敌生物}S_2\{x 的天敌生物\}

那么我们就可以按照普通并查集的方式,将符合上述性质的与 x+knx+kn 所在的集合合并即可归类。

总结

生动的理解起来,同样是有多元的关系维度,这种操作我们似乎是可以在分层图中体会到类似的思想,但回归集合处理的本质:

  • 将 x+knx+kn 作为某个特定关系的代表元素,便于直接检索该集合并对其进行合并或查询操作
C++
#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;
}
原文