[POJ1182] [NOI2001] 食物链 [带权并查集]

题目是中文的
( 1 ≤ N ≤ 5 ∗ 1 0 4 , 1 ≤ K ≤ 1 0 5 ) (1\le N\le 5*10^4,1\le K\le 10^5) (1N5104,1K105)

题目给出的条件 ( B → A , C → B , A → C ) (B \to A,C \to B,A \to C) (BA,CB,AC)是很重要的

它保证了 X → Y X \to Y XY Y → Z → X Y \to Z \to X YZX

于是 Y → X Y\to X YX X → Z → Y X \to Z \to Y XZY

那么我们可以这么表示: X → Y X \to Y XY ( V a l [ X ] + 1 ) % 3 = V a l [ Y ] (Val[X]+1)\%3=Val[Y] (Val[X]+1)%3=Val[Y]

Y → X Y \to X YX ( V a l [ X ] + 2 ) % 3 = V a l [ Y ] (Val[X]+2)\%3=Val[Y] (Val[X]+2)%3=Val[Y]

所以在这样的规定下,对于关系 F a t h e r [ X ] = Y Father[X]=Y Father[X]=Y

V a l [ X ] = { 0 , X = Y 1 , X → Y 2 , Y → X Val[X]=\begin{cases}0,X=Y\\1,X\to Y\\2,Y\to X\end{cases} Val[X]=0,X=Y1,XY2,YX

依此建立带权并查集。

当然,因为题目 D D D的定义,所以实际上为了方便我是这么规定的

V a l [ X ] = { 0 , X = Y 1 , Y → X 2 , X → Y Val[X]=\begin{cases}0,X=Y\\1,Y\to X\\2,X\to Y\end{cases} Val[X]=0,X=Y1,YX2,XY

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<algorithm>
#include<cmath>
using namespace std;
int N,K,Ans=0;
int fa[50005]={},val[50005]={};
int find(int x)
{
	if(fa[x]==x)return x;
	else
	{
		int t=find(fa[x]);
		val[x]=(val[x]+val[fa[x]])%3;
		return fa[x]=t;
	}
}
int main()
{
	scanf("%d%d",&N,&K);
	for(int i=0;i<=N;++i)fa[i]=i;
	register int R,X,Y,fX,fY;
	while(K--)
	{
		scanf("%d%d%d",&R,&X,&Y); --R;
		if((R&&(X==Y))||(X>N)||(Y>N)){++Ans;continue;}
		fX=find(X),fY=find(Y);
		if(fX!=fY)
		{
			fa[fX]=fY;
			val[fX]=(val[Y]+R-val[X]+3)%3;
		}
		else if(((val[X]-val[Y]+3)%3)!=R)++Ans;
	}
	printf("%d",Ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值