运用向量传递关系的思想,太妙了~
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn = 50010;
struct Node
{
int pre;
int relation;
}p[maxn];
int n, k;
int findfa(int x)
{
int temp;
if(x == p[x].pre)
return x;
temp = p[x].pre;
p[x].pre = findfa(temp);
p[x].relation = (p[x].relation + p[temp].relation) % 3; //great
return p[x].pre;
}
void init()
{
for(int i = 1; i <= n; i++)
{
p[i].pre = i;
p[i].relation = 0;
}
}
int main()
{
int ope, a, b;
cin >> n >> k;
int sum = 0;
init();
for(int i = 1; i <= k; i++)
{
scanf("%d%d%d", &ope, &a, &b);
if(a > n || b > n)
{
sum++;
continue;
}
if(ope == 2 && a == b)
{
sum++;
continue;
}
int root1, root2;
root1 = findfa(a);
root2 = findfa(b);
if(root1 != root2)
{
p[root2].pre = root1;
p[root2].relation = (p[a].relation + (ope - 1) + 3 - p[b].relation) % 3;
}
else
{
if(ope == 1 && p[a].relation != p[b].relation)
{
sum++;
continue;
}
else if(ope == 2 && (p[a].relation + (ope - 1) + 3 - p[b].relation) % 3 != 0)
{
sum++;
continue;
}
}
}
cout << sum << endl;
return 0;
}