codeforces 706D (字典树)

题目链接:http://codeforces.com/problemset/problem/706/D

题意:q次操作,可以向多重集中增添,删除,询问异或最大值。

思路:转化为二进制用字典树存储,数字从高位开始,并全部固定位30位。

#include<bits/stdc++.h>
using namespace std;
const int N=2e5 + 5;
int now = 1 ,Trie[N<<5][2] ,num[N<<5];
void Insert(int x)
{
    for(int i = 29 ,cur = 1 ; i >= 0 ;i--)
    {
        int tmp=(x >> i) & 1;
        if(!Trie[cur][tmp])
            Trie[cur][tmp] = ++now;
        cur = Trie[cur][tmp];
        num[cur]++;
    }
}
void Delete(int x)
{
    for(int i = 29 ,cur = 1 ;i >= 0 ;i--)
    {
        cur = Trie[cur][(x>>i)&1];
        num[cur]--;
    }
}
int query(int x)
{
    int ans=0;
    for(int i = 29 ,cur = 1 ;i >= 0 ;i--)
    {
        int tmp = (x >> i) & 1;
        if(num[Trie[cur][tmp^1]])
        {
            ans += (1<<i);
            cur = Trie[cur][tmp^1];
        }
        else
            cur = Trie[cur][tmp];
    }
    return ans;
}
int main()
{
    int q;
    scanf("%d",&q);
    Insert(0);
    char c;
    while(q--)
    {
        int x;
        scanf(" %c %d" ,&c ,&x);
        if(c == '+')
            Insert(x);
        if(c == '-')
            Delete(x);
        if(c == '?')
            printf("%d
" ,query(x));
    }
    return 0;
}

关于字典树:http://blog.csdn.net/u011787119/article/details/46991691

原文地址:https://www.cnblogs.com/westwind1005/p/5975193.html