并查集

测谎话,并查集的基础作用,我们开个3 * n的数组,每n个元素看成是同类,其余跨种族。

我们把输入的x和y进行找种族,如果存在冲突+1即可,雨巨也教的比较明白了,白嫖课大家可以去康康吖。

安利一波江大佬的带权并查集不用开3 * n的空间,保存n的大小,对3取模。传送门


#pragma GCC target("avx,sse2,sse3,sse4,popcnt")
#pragma GCC optimize("O2,O3,Ofast,inline,unroll-all-loops,-ffast-math")
#include <bits/stdc++.h>
using namespace std;
#define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define all(vv) vv.begin(), vv.end()
#define endl "\n"
typedef long long ll; typedef unsigned long long ull; typedef long double ld;
const ll MOD = 1e9 + 7;
inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar())    s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; }
inline void write(ll x) { if (!x) { putchar('0'); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-');    int cnt = 0;    while (tmp > 0) { F[cnt++] = tmp % 10 + '0';        tmp /= 10; }    while (cnt > 0)putchar(F[--cnt]); }
inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll qpow(ll a, ll b) { ll ans = 1;    while (b) { if (b & 1)    ans *= a;        b >>= 1;        a *= a; }    return ans; }    ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; }
inline int lowbit(int x) { return x & (-x); }

const int N = 5e4 + 7;
int fa[N * 3];

int find(int x) {
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}

void merge(int a, int b) {
    fa[find(a)] = find(b);
}

int main() {
    int n = read(), k = read();
    int ans = 0;
    for (int i = 1; i <= 3 * n; ++i)    fa[i] = i;
    for (int i = 1; i <= k; ++i) {
        int op = read(), x = read(), y = read();
        if (x > n or y > n) {
            ++ans;    continue;
        }
        if (op & 1) {
            if (find(x) == find(y + n) or find(x) == find(y + n + n)) {
                ++ans;    continue;
            }
            merge(x, y);
            merge(x + n, y + n);
            merge(x + n + n, y + n + n);
        }
        else {
            if (find(x) == find(y) or find(x) == find(y + n + n)) {
                ++ans;    continue;
            }
            merge(x, y + n);
            merge(x + n, y + n + n);
            merge(x + n + n, y);
        }
    }
    cout << ans << endl;
    return 0;
}