题目是中文的
( 1 ≤ N ≤ 5 ∗ 1 0 4 , 1 ≤ K ≤ 1 0 5 ) (1\le N\le 5*10^4,1\le K\le 10^5) (1≤N≤5∗104,1≤K≤105)
题目给出的条件 ( B → A , C → B , A → C ) (B \to A,C \to B,A \to C) (B→A,C→B,A→C)是很重要的
它保证了 X → Y X \to Y X→Y则 Y → Z → X Y \to Z \to X Y→Z→X
于是 Y → X Y\to X Y→X则 X → Z → Y X \to Z \to Y X→Z→Y
那么我们可以这么表示: X → Y X \to Y X→Y即 ( 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 Y→X即 ( 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,X→Y2,Y→X
依此建立带权并查集。
当然,因为题目 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,Y→X2,X→Y
#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;
}