题解:AT_abc249_g [ABC249G] Xor Cards

· · 题解

Solution

将 (x_i,y_i) 作为 y_i\times2^{30}+x_i 插入线性基,线性基里的 \mathcal{O}(\log V) 个数可以表示出原序列任意的数,只保留这些数答案不变(如果异或出了 0 也要保留)。将这些数还原回 (x_i,y_i),得到了新的序列。

于是我们花费了 \mathcal{O}(n\log V) 的时间,将 n 缩小到了 \mathcal{O}(\log V)。

可以发现,y_i 最高位互不相同。将 (x_i,y_i) 按 y_i 从大到小排序,每次贪心判断能否取。具体地,维护当前 x_i,y_i 的异或和 sm,rs,处理出 [i+1,n] 的线性基 B:

注意判无解:强制取一个数 i,然后判断它在 [i+1,n] 的线性基 B 中最终是否可以 \le k。如果存在这样的 i,那么有解。

处理出后缀线性基,复杂度 \mathcal{O}(n\log V+\log^2V)。

Code

#include <bits/stdc++.h>
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
using namespace std;
namespace Milkcat {
    typedef long long LL;
    typedef pair<LL, LL> pii;
    const int N = 1e6 + 5, P = 60;
    struct LBase {
        LL b[P + 3]; Linear() { mems(b, 0); }
        int ins(LL x) { DEP(i, P, 0) if (x >> i & 1) if (b[i]) x ^= b[i]; else return b[i] = x, i; return 0; }
        LL askmx(LL x) { DEP(i, P, 0) x = max(x, x ^ b[i]); return x; }
        LL askmn(LL x) { DEP(i, P, 0) x = min(x, x ^ b[i]); return x; }
    } C, B[P + 5];
    LL n, m, k, x, ck, a[N], b[N];
    vector<pii> s;
    bool chk(int t, LL v) { return (B[t].askmn(v) <= k); }
    int main() {
        cin >> n >> k;
        REP(i, 1, n) {
            cin >> a[i] >> b[i];
            int x = C.ins(b[i] << 30 | a[i]);
            if (!x && !SZ(s)) s.pb(0, 0);
        }
        REP(i, 0, P) {
            LL x = C.b[i];
            if (x > 0) s.pb(x >> 30, x & ((1 << 30) - 1));
        }
        sort(ALL(s), greater<pii>()), m = SZ(s) - 1;
        DEP(i, m, 0) B[i] = B[i + 1], B[i].ins(s[i].se);
        REP(i, 0, m) ck |= chk(i + 1, s[i].se);
        if (!ck) { cout << "-1\n"; return 0; }
        LL rs = 0, sm = 0;
        REP(i, 0, m) {
            auto [x, y] = s[i];
            int c1 = chk(i + 1, sm ^ y), c2 = chk(i + 1, sm);
            if ((c1 && (rs ^ x) > rs) || !c2) rs ^= x, sm ^= y;
        }
        cout << rs << '\n';
        return 0;
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int T = 1;
    while (T --) Milkcat::main();
    return 0;
}