您的位置:首页 > 其它

CSU 1216: 异或最大值(字典树+贪心)

2016-09-09 22:41 316 查看
1216: 异或最大值

Time Limit: 2 Sec Memory Limit: 128 MB

Description

给定一些数,求这些数中两个数的异或值最大的那个值

Input

第一行为数字个数n,1 <= n <= 10 ^ 5。接下来n行每行一个32位有符号非负整数。

Output

任意两数最大异或值

Sample Input

3

3

7

9

Sample Output

14

题解:

对每一个数的二进制直接建立字典树,然后贪心即可。

#include<bits/stdc++.h>
using namespace std;

const int maxn=1e5+5;

struct note {
struct note *Next[2];
int Data;
note() {
Next[0]=Next[1]=NULL;
}
};
int Bit[31],S,ans,val;

void Insert(struct note *&r) {
note *p=r;
for(int i=30; i>=0; --i) {
if(p->Next[Bit[i]]==NULL) {
note *temp=new note();
p->Next[Bit[i]]=temp;
}
p=p->Next[Bit[i]];
}
}

int Query(struct note *&r) {
struct note *p=r;
int tans=0;
for(int i=30; i>=0; --i) {
if(p->Next[Bit[i]^1]!=NULL){
tans|=(1<<i),p=p->Next[Bit[i]^1];
}else if(p->Next[Bit[i]]!=NULL){
p=p->Next[Bit[i]];
}else return tans;
}
return tans;
}

void reSolve(){
S=0;
while(val){
Bit[S++]=val&1;
val>>=1;
}
while(S<=30){
Bit[S++]=0;
}
}

int main() {
int n;
while(scanf("%d",&n)==1) {
struct note *Root=new note();
ans=0;
for(int i=0;i<n;++i){
scanf("%d",&val);
reSolve();
Insert(Root);
ans=max(ans,Query(Root));
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: