CSU 1216 异或最大值(01Trie)

字典树,碰到了一个同类型但比这个难点的题,不会做,先找个简单的来练练,铺垫下。01Trie就是每层只有0和1的字典树。把一个数字的二进制看成字符串,从高位到低位放进字典树。
http://blog.csdn.net/fuyukai/article/details/50366133
这里讲的很详细。

——-2017.11.06——————
突然想到,这题代码是错误的,数据水,还是过了,query那里写错了,正确代码见:http://blog.csdn.net/gyhguoge01234/article/details/78357625
虽然不是一个题了,但大致一样

#include <stdio.h>
#include <string.h>

const int MAXN = 1e5+10;

template<typename T>
T max(const T a, const T b)
{
    if(a > b) return a;
    return b;
}

struct Trie
{
    int next[MAXN*31][2];
    int root,sz;

    void init()
    {
        memset(next,-1,sizeof(next));
        sz = 0;
        root = 0;
    }

    void insert(int x)
    {
        int now = root;
        for(int i = 31; i >= 0; --i)
        {
            int t = (x>>i)&1;
            if(next[now][t] == -1)
                next[now][t] = ++sz;
            now = next[now][t];
        }
    }

    int query(int x)
    {
        int ret = 0,t;
        int now = root;
        for(int i = 31; i >= 0; --i)
        {
            t = (x>>i)&1;
            if(next[now][!t] != -1)
                t = !t;
            ret |= t<<i;
            now = next[now][t];
        }
        return ret;
    }
};

Trie t;

int main()
{
    int n,res,num;
    while(scanf("%d",&n) != EOF)
    {
        t.init();
        res = -1;
        for(int i = 0; i < n; ++i)
        {
            scanf("%d",&num);
            t.insert(num);
            res = max(res,num^t.query(num));
        }
        printf("%d\n",res);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值