Vasiliy's Multiset CodeForces - 706D 字典樹

01字典樹模板題自己都沒做出來。。多看看理解一下吧
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=200005;

int tot;
int root;
struct node
{
    int son[2];
    int num;
}tree[40*maxn];
int newnode()
{
    tot++;
    tree[tot].son[0]=tree[tot].son[1]=0;
    return tot;
}
void inser(int x)
{
    int now=root;
    for(int i=31;i>=0;i--)
    {
        int tmp=!!(x&(1<<i));
        if(tree[now].son[tmp]==0)tree[now].son[tmp]=newnode();
        tree[tree[now].son[tmp]].num++;
        now=tree[now].son[tmp];
    }
}
void delet(int x)
{
    int now=root;
    int tmp;
    for(int i=31;i>=0;i--)
    {
         tmp=!!(x&(1<<i));
        tree[tree[now].son[tmp]].num--;
        now=tree[now].son[tmp];
    }

}
long long  query(int x)
{
    long long  ans=0;
    int now=root;
    for(int i=31;i>=0;i--)
    {
        int tmp=!!!(x&(1<<i));
        if(tree[now].son[tmp]!=0&&tree[tree[now].son[tmp]].num>0)
        {
            ans+=tmp*(1<<i);
            now=tree[now].son[tmp];
        }
        else
        {
            ans+=(!tmp)*(1<<i);
            now=tree[now].son[!tmp];
        }
    }
        return ans;

}
int main()
{
    int q;
    while(cin>>q)
    {

        tot=-1;
        root=newnode();
        memset(tree,0,sizeof(tree));
        inser(0);
        for(int i=0;i<q;i++)
        {
            char x;
            long long  y;
            cin>>x>>y;
           // cout<<x<<y<<endl;
            if(x=='+')inser(y);
            else if(x=='-')delet(y);
            else
            {
                long long z=y^query(y);
                cout<<z<<endl;
            }
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章