http://poj.org/problem?id=1182
并查集。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 50005
int n,k,p[N],t[N];
void init()
{
int i;
for (i=1;i<=n;i++)
{
p[i]=i;
t[i]=0;
}
}
int root(int s)
{
if (p[s]==s) return s;
int st=p[s];
p[s]=root(p[s]);
t[s]=(t[s]+t[st])%3;
return p[s];
}
void un(int x,int y,int z)
{
int rx,ry;
rx=root(x);
ry=root(y);
p[ry]=rx;
t[ry]=(t[x]-z-t[y]+6)%3;
}
int main()
{
freopen("a","r",stdin);
int i;
scanf("%d%d",&n,&k);
init();
int sum=0,x,y,z;
for (i=1;i<=k;i++)
{
scanf("%d%d%d",&z,&x,&y);
if (x>n || y>n) sum++;
else if (x==y && z==2) sum++;
else
{
int rx,ry;
rx=root(x);
ry=root(y);
if (rx==ry)
{
if (z==1 && t[x]!=t[y]) sum++;
if (z==2 && (t[x]+3-t[y])%3!=1) sum++;
}
else un(x,y,z-1);
}
}
cout<<sum<<endl;
return 0;
}