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;
}