[HDU](5536)Chip Factory ---- 0-1字典树★

版权声明:本文为博主原创文章,转载请预先通知博主(〃'▽'〃)。 https://blog.csdn.net/m0_37624640/article/details/82934015

题目传送门

Hint: 2015ACM/ICPC亚洲区长春站-重现赛

做法:

  • 0-1字典树模板题,因为题目中要求,i,j,k是不同的,所以当我们选取两个数求和找与这个值异或最大的数时,要先把这俩求和的数从字典树中删掉,求完和,再增加。

AC代码:

#include<bits/stdc++.h>
#define IO          ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define pb(x)       push_back(x)
#define sz(x)       (int)(x).size()
#define sc(x)       scanf("%d",&x)
#define pr(x)       printf("%d\n",x)
#define abs(x)      ((x)<0 ? -(x) : x)
#define all(x)      x.begin(),x.end()
#define mk(x,y)     make_pair(x,y)
#define debug       printf("!!!!!!\n")
#define fin         freopen("in.txt","r",stdin)
#define fout        freopen("out.txt","w",stdout)
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int mod = 1e9+7;
const double PI = 4*atan(1.0);
const int maxm = 1e8+5;
const int maxn = 3e5+5;
const int INF = 0x3f3f3f3f;
int a[maxn];
int trie[maxn][2];
int val[maxn];
int cnt,ans;
//0-1字典树,用来求异或最大
inline void add(int s,int c)
{
    int rt = 0;
    for(int i=30;i>=0;i--)
    {
        int x = (s>>i)&1;
        if(trie[rt][x] == 0) trie[rt][x] = ++cnt;
        rt = trie[rt][x];
        val[rt]+=c;
    }
}
inline int query(int s)
{
    int rt = 0,res = 0;
    for(int i=30;i>=0;i--)
    {
        int x = (s>>i)&1;
        if(trie[rt][x^1] && val[trie[rt][x^1]]){ //x^1这种写法很关键!! 如果要查数该位是0,那么最优的是被查数的该位是1  (贪心思想)
            res|=(1<<i);
            rt = trie[rt][x^1];
        }else rt = trie[rt][x];
    }
    return res;
}
int main()
{
    // fin;
    int t;sc(t);
    while(t--)
    {
        ans = -1,cnt = 0;
        memset(trie,0,sizeof(trie));
        memset(val,0,sizeof(val));
        int n;sc(n);
        for(int i=0;i<n;i++)
        {
            sc(a[i]);
            add(a[i],1);
        }
        for(int i=0;i<n;i++)
        {
            add(a[i],-1);
            for(int j=i+1;j<n;j++)
            {
                add(a[j],-1);
                ans = max(ans,query(a[i]+a[j]));
                add(a[j],1);
            }
            add(a[i],1);
        }
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37624640/article/details/82934015
今日推荐