[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)

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

它保证了 X Y X \to Y Y Z X Y \to Z \to X

于是 Y X Y\to X X Z Y X \to Z \to Y

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

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

所以在这样的规定下,对于关系 F a t h e r [ 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}

依此建立带权并查集。

当然,因为题目 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}

#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;
}

猜你喜欢

转载自blog.csdn.net/Estia_/article/details/82873162