异或树(完善中)

基础异或字典树

传送门

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m, a[N], son[N * 32][2], idx, val[N * 32];
inline void insertt(int x)
{
    int p = 0;
    for(int i = 30; i >= 0; --i)
    {
        //x >> i & 1 判断该插入位置是0还是1
        int &s = son[p][(x >> i) & 1];
        if(!s) s = ++idx;
        p = s;
    }
    val[p] = x;
}
inline int query(int x)
{
    int res = 0, p = 0;
    for(int i = 30; i >= 0; --i)
    {
        int s = (x >> i) & 1;
        //是否有相反的值,使得异或为1
        if(son[p][!s]) p = son[p][!s];
        else p = son[p][s];
    }
    return val[p];
}
signed main()
{
    ios::sync_with_stdio(false), cin.tie(0);
    int T;
    cin >> T;
    int tag = 0;
    while(T--)
    {
        cout << "Case #" << ++tag << ":\n";
        idx = 0;
        memset(son, 0, sizeof son);
        memset(val, 0, sizeof val);
        cin >> n >> m;
        for(int i = 1; i <= n; ++i) cin >> a[i], insertt(a[i]);
        int x;
        while(m-- && cin >> x) cout << query(x) << "\n";
    }
    return 0;
}

posted @ 2022-06-28 11:54  std&ice  阅读(81)  评论(0)    收藏  举报