字典树

区域赛第一场:水题

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;
#define INF 0x3f3f3f3f
#define N 1000 + 10
#define M 40000 + 10

int n, a[N], top, tree[M][3], digit[M], val[M];

void init()
{
    scanf("%d", &n);
    for(int i = 0; i < n; i++) scanf("%d", a + i);
    top = 1;
    memset(tree[0], 0, sizeof tree[0]);
    memset(val, 0, sizeof val);
}

void Insert(int x, int v)
{
    int u = 0, pos = 0;
    memset(digit, 0, sizeof digit);
    while(x)
    {
        digit[pos++] = x & 1;
        x >>= 1;
    }
    pos = 30;
    reverse(digit, digit + pos);
    for(int i = 0; i < pos; i++)
    {
        int c = digit[i];
        if(!tree[u][c])
        {
            memset(tree[top], 0, sizeof tree[top]);
            val[top] = 0;
            tree[u][c] = top++;
        }
        u = tree[u][c];
        val[u] += v;
    }

}


int solve(int x)
{
    int pos = 0, u = 0;
    int res[40];
    memset(digit, 0, sizeof digit);
    while(x)
    {
        digit[pos++] = x & 1;
        x >>= 1;
    }
    pos = 30;
    reverse(digit, digit + pos);
    for(int i = 0; i < pos; i++)
    {
        int c = digit[i] ^ 1;
        if(val[tree[u][c]])
        {
            u = tree[u][c];
            res[i] = c;
        }
        else
        {
            u = tree[u][c ^ 1];
            res[i] = c ^ 1;
        }
    }
    int ret = 0;
    for(int i = 0; i < pos; i++) cout << res[i] << " ";
    cout << endl;
    for(int i = 0; i < pos; i++)
        ret += res[i] * (1 << (pos - i - 1));
    return ret;
}

int main()
{
    int _T;
    scanf("%d", &_T);
    while(_T--)
    {
        init();
        for(int i = 0; i < n; i++)
            Insert(a[i], 1);
        int ans = -INF;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < i; j++)
            {
                Insert(a[i], -1);
                Insert(a[j], -1);
                int tmp = a[i] + a[j];
                tmp = tmp ^ solve(tmp);
                ans = max(ans, tmp);
                Insert(a[i], 1);
                Insert(a[j], 1);
            }
        printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(ACM)