HDU5536字典树贪心

题意:给出N个数,选出3个数ai,aj,ak(i != j != k)使(ai + aj) ^ ak 有最大值。

题解:暴力解法N^3据说也能过?正解是O(N^2), 首先对N个树建立字典树, 肯定是2进制位从高位到低位,很明显用栈非常方便,对数分解时,但是STL的栈竟然超时,具体实现看代码? 然后枚举2个数相加在树上找,注意这里先把枚举的两个数,从树上先删除在插入。然后就是很常规讨论下,是1最好最0,是0走1.

#include <bits/stdc++.h>

using namespace std;
#define SZ(X) ((int)X.size())
#define mp make_pair
#define pb push_back
#define RALL(X) X.rbegin(),X.rend()
#define ALL(X) X.begin(),X.end()

using ll = long long ;
using ld = long double ;
const int N = 2E5 + 7;
int tree[N][2];
int vis[N];
int a[1024], tot;
int sta[31];
void insert(int n)
{
    int m = n;
    int sz = 0;
    while(m) {
        sta[sz++] = m & 1;
        m >>= 1;
    }
    while(sz < 31) sta[sz ++] = 0;
    int now = 0;
    while(sz) {
        int top = sta[--sz] ;
        if(!tree[now][top]) tree[now][top] = ++ tot;
        now = tree[now][top];
        vis[now] ++;
    }
}

void erase(int n)
{
    int m = n;
    int sz = 0;
    while(m) {
        sta[sz++] = m & 1;
        m >>= 1;
    }
    while(sz < 31) sta[sz ++] = 0;
    int now = 0;
    while(sz) {
        int top = sta[--sz];
        vis[tree[now][top]] --;
        now = tree[now][top];
    }
}

int tpow[32];
int solve(int n)
{
    int m = n;
    int sz = 0;
    while(m) {
        sta[sz++] = m & 1;
        m >>= 1;
    }
    while(sz < 31) sta[sz ++] = 0;
    int now = 0;
    for(int i = 30;i >= 0;i --) {
        int top = sta[i];
        if(top == 0) {
            if(vis[tree[now][1]]) {
                n += tpow[i];
                now = tree[now][1];
            } else {
                now = tree[now][0];
            }
        } else {
            if(!vis[tree[now][0]]) {
                n -= tpow[i];
                now = tree[now][1];
            } else {
                now = tree[now][0];
            }
        }
    }
    return n;
}

int main()
{
    std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); cout << fixed;
    int T;
    tpow[0] = 1;
    for(int i = 1; i <= 31; i ++) tpow[i] = tpow[i-1] * 2;
    cin >> T;
    while(T --) {
        int n;
        cin >> n;
        for(int i = 1; i <= n; i ++) cin >> a[i];
        tot = 0;
        int ans = -1;
        for(int i = 1; i <= n; i ++) insert(a[i]);
        for(int i = 1; i <= n; i ++) {
            erase(a[i]);
            for(int j = i + 1; j <= n; j ++) {
                int mmp = a[i] + a[j];
                erase(a[j]);
                ans = max(ans, solve(mmp)) ;
                insert(a[j]);
            }
            insert(a[i]);
        }
        cout << ans << "\n";
        for(int i = 0;i <= tot;i ++) {
            tree[i][0] = tree[i][1] = vis[i] = 0;
        }
    }
    return 0;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值