http://poj.org/problem?id=1182
分析:
rank[x]=(rank[x]+rank[t])%3;
rank[t1]=(rank[y]-rank[x]+d-1+3)%3;
参考:http://cavenkaka.iteye.com/blog/1489588
#include<iostream>
#include<cstdio>
using namespace std;
const int NUM=50005;
int father[NUM],rank[NUM];
int Find(int x)
{
if(x!=father[x])
{
int t=father[x];
father[x]=Find(father[x]);
rank[x]=(rank[x]+rank[t])%3;//某结点和爷爷的关系由它和父亲的关系决定,每一层相差1(0:同类,1:吃父亲,2:被吃)
}
return father[x];
}
void Union(int x,int y,int d)
{
int t1=Find(x),t2=Find(y);
father[t1]=t2;
rank[t1]=(rank[y]-rank[x]+d-1+3)%3;
}
int main()
{
int i,x,y,d,count,N,K;
scanf("%d%d",&N,&K);
for(i=0;i<=N;i++)
{father[i]=i;rank[i]=0;}
count=0;
while(K--)
{
scanf("%d%d%d",&d,&x,&y);
if(x>N||y>N||(d==2&&x==y)) {count++;continue;}
int t1=Find(x),t2=Find(y);
if(t1==t2)
{
if((rank[x]-rank[y]+3)%3!=d-1) count++;//0->2,1->0,2->1
}
else
Union(x,y,d);
}
printf("%d\n",count);
return 0;
}