根据我们开三个集合:X,Y,Z.
这三个集合的满足:X吃Y吃Z吃X,也就是下图
也就是开三倍长度的并查集,X:1-n,Y:n+1-2n,Z:2n+1-3*n
对于a,b两个元素,如果是同类那么我们union(a,b),同时知道被他们吃的元素a+n,b+n也是同类,所以union(a+n,b+n)
同时知道被a+n,b+n吃的元素也是同类,所以union(a+2n,b+2n)(同类吃的元素也是同类,能吃同类的元素也是同类)
如果 a 吃 b 那么 a吃的元素和b是同类 也就是 union(a+n,b) , 吃b的元素和a也是同类 也就是union(b+2n,a)
吃a的元素和b吃的元素是同类 也就是 union(a+2n,b+n)
AC代码
#include <iostream>
#include <cstring>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include<queue>
#include<math.h>
using namespace std;
// 初始化并查集
#define N 200005
int father[N];
void init() {
for (int i = 0; i < N; i++)
father[i] = i;
}
int getfather(int x) {
if (x != father[x])
father[x] = getfather(father[x]);
return father[x];
}
void un(int x, int y) {
x = getfather(x);
y = getfather(y);
if (x != y)
father[x] = y;
}
int main()
{
int n, k;
scanf("%d %d", &n, &k);
init();
int ans = 0;
while (k--)
{
int m, x, y;
scanf("%d %d %d", &m, &x, &y);
if (x > n || y > n)
{
ans++;
continue;
}
if (m == 1)
{
if (getfather(x) == getfather(y + n) || getfather(x) == getfather(y + 2 * n))
{
ans++;
}
else
{
un(x, y);
un(x + n, y + n);
un(x + 2 * n, y + 2 * n);
}
}
else
{
if (getfather(x) == getfather(y) || getfather(x) == getfather(y + n))
{
ans++;
}
else
{
un(x, y + 2*n);
un(x + n, y);
un(x + 2 * n, y + n);
}
}
}
cout << ans << endl;
}