POJ1182
思路:
对于每只动物创建3个元素i-A,i-B,i-C,并用着3*n的元素建立并查集,维护一下信息
i-x表示“i属于种类x”
并查集里的每一个组表示组内的所有元素代表的情况都有可能同时发生或者不发生
只需按照以下操作就可以
第一:x和y属于同一类.....,合并x-A和y-A, x-B和y-B,x-C和y-C
第二:x吃y...................合并x-A和y-B, x-B和y-C, x-C和y-A
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 150000+5;
int n, k, son, tmp;
int pre[maxn];
void init(int s)
{
for(int i = 0; i <= s; i++)
pre[i] = i;
}
int find(int root)
{
son = root;
while(root != pre[root])
root = pre[root];
while(son != root) //路径压缩
{
tmp = pre[son];
pre[son] = root;
son = tmp;
}
return root;
}
void join(int root1, int root2)
{
root1 = find(root1);
root2 = find(root2);
if(root1 != root2)
pre[root1] = root2;
}
bool same(int x, int y)
{
return find(x) == find(y);
}
int main()
{
cin >> n >> k;
init(n * 3);
int ans = 0, x, y, t;
for(int i = 0; i < k; i++)
{
scanf("%d %d %d", &t, &x, &y);
if(x <= 0 || x > n || y <= 0 || y > n || t == 2 && x == y)
{
ans++;
continue;
}
if(t == 1)
{
if(same(x, y + n) || same(x, y + 2 * n))
{
ans++;
continue;
}
else
{
join(x, y);
join(x + n, y + n);
join(x + n * 2, y + n * 2);
}
}
else
{
if(same(x, y) || same(x, y + 2 * n))
{
ans++;
continue;
}
else
{
join(x, y + n);
join(x + n, y + 2 * n);
join(x + 2 * n, y);
}
}
}
printf("%d\n", ans);
return 0;
}