hdu 5536 trie树

hdu 5536
题意:给n个数字,求 max{(Si+Sj)  Sk}ijk
思路:建trie树,遍历所有的Si+Sj,每次查询时删除Si和Sj,查完再加回去,这样可以降低查询的回溯时间。另外数组开大了初始化会慢上几秒。。

/****************************************************
  >Created Date: 2015-10-01-13.34.56
  >My Soul, Your Beats!
****************************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <algorithm>
using namespace std;

typedef long long LL;

const int INF = 1 << 30;
const long long  LINF = 1LL << 50;
const int M = 1e3 + 10;
const int N = 3e4 + 10;
const double PI = acos(-1.0);
const double eps = 1e-6;

struct Tree{
    int l, r, cnt, v;
}tree[N];
int tcnt = 0;
void Insert(int a, int now, int tid){
    tree[tid].cnt++;
    if(now == -1){
        tree[tid].v = a;
        return ;
    }
    if(a & (1 << now)){
        if(tree[tid].r == 0) tree[tid].r = ++tcnt;
        Insert(a, now - 1, tree[tid].r);
    }
    else {
        if(tree[tid].l == 0) tree[tid].l = ++tcnt;
        Insert(a, now - 1, tree[tid].l);
    }
}
void Delete(int a, int now, int tid){
    tree[tid].cnt--;
    if(now == -1){
        return ;
    }
    if(a & (1 << now)) Delete(a, now - 1, tree[tid].r);
    else Delete(a, now - 1, tree[tid].l);
}
int ret;
bool findans(int a, int now, int tid){
    if(now == -1){
        if(tree[tid].cnt > 0) {
            ret = tree[tid].v;
            return true;
        }
        return false;
    }
    if(a & (1 << now)){
        if(tree[tid].r != 0 && tree[tree[tid].r].cnt)
            if(findans(a, now - 1, tree[tid].r)) return true;
        findans(a, now - 1, tree[tid].l);
    }
    else {
        if(tree[tid].l != 0 && tree[tree[tid].l].cnt)
            if(findans(a, now - 1, tree[tid].l)) return true;
        findans(a, now - 1, tree[tid].r);
    }
}
int seq[M];
int main(){
    #ifndef ONLINE_JUDGE
        freopen("in.in", "r", stdin);
    #endif // ONLINE_JUDGE
    int t;
    scanf("%d", &t);
    while(t--){
        int n;
        scanf("%d", &n);
        memset(tree, 0, sizeof tree);
        tcnt = 0;
        for(int i = 0; i < n; i++) {
            scanf("%d", &seq[i]);
            Insert(seq[i], 30, 0);
        }
        int ans = 0;
        ret = 0;
        for(int i = 0; i < n; i++){
            Delete(seq[i], 30, 0);
            for(int j = i + 1; j < n; j++){
                Delete(seq[j], 30, 0);
                int a = (seq[i] + seq[j]) ^ ((1LL << 31) - 1);
                findans(a, 30, 0);
                ans = max(ans, (seq[i] + seq[j]) ^ ret);
                Insert(seq[j], 30, 0);
            }
            Insert(seq[i], 30, 0);
        }
        printf("%d\n", ans);
    }
    return 0;
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/elicococoo/article/details/49561963
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞