D. Dr. Evil Underscores(思维+贪心+字典树dfs)

https://codeforces.com/problemset/problem/1285/D


思路:

异或的最大值,是字典树。由于X是任意的,并且不好构造。平时看到最大值最小是二分答案。现在我们需要用字典树来维护这个最大值。

假设最小值的答案是ans,那么对于第i位,如果n个数中第i位为0和1同时存在。Ans就一定要加2^i(因为X不管该位怎么拿都是要有对答案的2^i的贡献) 

如果只有0,那么可以往0跑(X该位构造0,这样答案就不会产生该位的2^i,而且从高到低的贪心是保证的)

只有1,那么可以往1跑(X该位构造1,ans该位不产生2^i的贡献)

于是上字典树

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL a[maxn];
LL tree[maxn*30][2];
///tire[i][j]=p 代表编号为i的节点的第j个孩子是编号为p的节点
LL tot=1,root=1;
void insert(LL x,LL add){
    LL p=root;
    for(LL i=30;i>=0;i--){
        LL t=x>>i&1;
        if(!tree[p][t]) tree[p][t]=++tot;
        p=tree[p][t];
    }
}
LL dfs(LL now,LL dep){
   LL k1=tree[now][0];LL k2=tree[now][1];LL res=0;
   if(!k1&&!k2) return 0;
   if(!k1&&k2){
      LL resR=dfs(tree[now][1],dep-1);
      return resR;
   }
   else if(k1&&!k2){
      LL resL=dfs(tree[now][0],dep-1);
      return resL;
   }
   else res+=(1<<dep)+min(dfs(tree[now][1],dep-1),dfs(tree[now][0],dep-1));
   return res;
}
int main(void){
   cin.tie(0);std::ios::sync_with_stdio(false);
   LL n;cin>>n;
   for(LL i=1;i<=n;i++) {
       cin>>a[i];
       insert(a[i],1);
   }
   cout<<dfs(1,30)<<"\n";
   return 0;
}


 

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/115382485