01字典树

字典树:又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串,所以经常被搜索引擎系统用于文本词频统计。他的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无畏的字符串比较,查询效率比哈希高)//具体见百度百科

基本操作:查找,插入和删除。

例题:http://codeforces.com/contest/706/problem/D

D. Vasiliy's Multiset

time limit per test

4 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Author has gone out of the stories about Vasiliy, so here is just a formal task description.

You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries:

  1. "+ x" — add integer x to multiset A.
  2. "- x" — erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query.
  3. "? x" — you are given integer x and need to compute the value                          , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.

Multiset is a set, where equal elements are allowed.

Input

The first line of the input contains a single integer q (1 ≤ q ≤ 200 000) — the number of queries Vasiliy has to perform.

Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1 ≤ xi ≤ 109). It's guaranteed that there is at least one query of the third type.

Note, that the integer 0 will always be present in the set A.

Output

For each query of the type '?' print one integer — the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.

Example

input

10
+ 8
+ 9
+ 11
+ 6
+ 1
? 3
- 8
? 3
? 8
? 11

output

11
10
14
13

 

 

就是求^的最大值。01字典树解决。

//搞不懂N是怎样算的 我让N=10e5mle

AC代码:

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

using namespace std;
typedef long long LL;
const int N = (2e5)*30;
const int INF = 0x3f3f3f3f;
int ch[N][2],cnt[N],tot,n;
int newnode()
{
    ++tot;
    memset(ch[tot],-1,sizeof(ch[tot]));
    return tot;
}
void add(int x,int t)
{
    int now=0;
    for(int i=29; i>=0; --i)
    {
        int nx=(x&(1<<i))?1:0;
        if(ch[now][nx]==-1)ch[now][nx]=newnode();
        now=ch[now][nx];
        cnt[now]+=t;
    }
}
int ask(int x)
{
    int now=0,ret=0;
    for(int i=29; i>=0; --i)
    {
        int nx=(x&(1<<i))?1:0;
        if(ch[now][nx^1]!=-1&&cnt[ch[now][nx^1]])
        {
            now=ch[now][nx^1];
            ret+=(1<<i);
        }
        else now=ch[now][nx];
    }
    return ret;
}
char op[5];
int main()
{
    tot=-1;
    newnode();
    add(0,1);
    scanf("%d",&n);
    while(n--)
    {
        int x;
        scanf("%s%d",op,&x);
        if(op[0]=='+')add(x,1);
        else if(op[0]=='-')add(x,-1);
        else printf("%d\n",ask(x));
    }
    return 0;
}

 

 

 

 

 

posted @ 2016-09-28 20:11  a_clown_cz  阅读(248)  评论(0)    收藏  举报