【codevs 3031】最富有的人

题目描述 Description

在你的面前有n堆金子,你只能取走其中的两堆,且总价值为这两堆金子的xor值,你想成为最富有的人,你就要有所选择。

输入描述 Input Description

第一行包含两个正整数n,表示有n堆金子。
第二行包含n个正整数,表示每堆金子的价值。

输出描述 Output Description

第一行包含一个正整数,表示能获得的最大总价值。

样例输入 Sample Input

10
1 2 3 4 5 6 7 8 9 10

样例输出 Sample Output

15

数据范围及提示 Data Size & Hint

n<=100000 每堆金子数<=2^31-1

//rainherat大神邀请我去做二分练习题,然后rand到了这题……我去……这是二分……?
嗯……
总而言之,这是一棵字典树……
正好,多久不打字典树了

咳咳,扯远了
用字典树去维护二进制位
tree[i][0]表示第i位是0
然后普通的字典树……
记得空间要大大大大大!!!!!
没个5’000’000你还敢做……?
就是这样
顺带一提,暴搜TLE
然后有个小剪枝,就是我可以按位从高到低建树,嗯
然后能朝两边走就朝两边走,走完就return,这显然是优的(想想看,为什么)
10000 > 1111
然后就好啦~

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 1000000 + 5;
int tree[MAXN][2];
int sz;
int num[MAXN];
void insert(int v)
{
    int x = 0;
    for(int i = 30;i >= 0;i --)
    {
        if(!tree[x][(v >> i) & 1])
            tree[x][(v >> i) & 1] = ++sz;
        x = tree[x][(v >> i) & 1];
    }
    num[x] = v;
    return;
}
int ans = 0;
void dfs(int x,int y)
{
    ans = max(ans,(num[x] ^ num[y]));
    if((tree[x][1] && tree[y][0]) || (tree[x][0] && tree[y][1]))
    {
        if(tree[x][1] && tree[y][0])
            dfs(tree[x][1],tree[y][0]);
        if(tree[x][0] && tree[y][1])
            dfs(tree[x][0],tree[y][1]);
        return;
    }
    if(tree[x][0] && tree[y][0])
        dfs(tree[x][0],tree[y][0]);
    if(tree[x][1] && tree[y][1])
        dfs(tree[x][1],tree[y][1]);
    return;
}
int n,k;
int main()
{
    scanf("%d",&n);
    for(int i = 1;i <= n;i ++)
        scanf("%d",&k),insert(k);
    dfs(0,0);
    printf("%d\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值