P2024 [NOI2001]食物链 题解

Link

P2024 [NOI2001]食物链

Solve

有点像团伙那道题,只是要分三类

我们定义
1~n表示自己的同类

n+1~2n表示自己的猎物

2n+1~3n表示自己猎物的猎物,也就是自己的天敌

主要思想拓展域并查集

有了这个思想代码就很简单了

Code

#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int fa[maxn*3],ans,N,M;
inline int read(){
	int ret=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-f;ch=getchar();}
	while(ch<='9'&&ch>='0')ret=ret*10+ch-'0',ch=getchar();
	return ret*f;
}
int get(int x){return x==fa[x]?x:fa[x]=get(fa[x]);}
int main(){
	freopen("P2024.in","r",stdin);
	freopen("P2024.out","w",stdout);
	N=read();M=read();
	for(int i=1;i<=N*3;i++)fa[i]=i;
	while(M--){
		int op=read(),x=read(),y=read();
		if(x>N||y>N){ans++;continue;}
		if(op==1){
			if(get(x)==get(y+N)||get(x+N)==get(y)){ans++;}
			else{
				fa[get(x)]=get(y);
				fa[get(x+N)]=get(y+N);
				fa[get(x+N+N)]=get(y+N+N);
			}
		}
		else {
			if(get(x)==get(y)||get(x)==get(y+N)){ans++;}
			else {
				fa[get(x)]=get(y+N+N);
				fa[get(x+N)]=get(y);
				fa[get(x+N+N)]=get(y+N);
			}
		}
	}
	printf("%d
",ans);
	return 0;
}
原文地址:https://www.cnblogs.com/martian148/p/13877062.html