题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4825
题意:找出集合中与X异或的最大值
01字典树模板题
代码:
#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 100000 + 5;
typedef long long LL;
int ch[32 * maxn][2];
LL value[32 * maxn];
int node_cnt;
inline void init(){
node_cnt = 1;
memset(ch[0],0,sizeof(ch));
}
inline void Insert(LL x){
int cur = 0;
for(int i = 32;i >= 0;--i){
int idx = (x >> i) & 1;
if(!ch[cur][idx]){
memset(ch[node_cnt],0,sizeof(ch[node_cnt]));
ch[cur][idx] = node_cnt;
value[node_cnt++] = 0;
}
cur = ch[cur][idx];
}
value[cur] = x;
}
inline LL Query(LL x){
int cur = 0;
for(int i = 32;i >= 0;--i){
int idx = (x >> i) & 1;
if(ch[cur][idx ^ 1]) cur = ch[cur][idx ^ 1];
else cur = ch[cur][idx];
}
return value[cur];
}
int main(){
int T,m,temp,n,ca = 0;
sf("%d",&T);
while(T--){
init();
sf("%d%d",&n,&m);
for(int i = 0;i < n;++i){
sf("%d",&temp);Insert(temp);
}
pf("Case #%d:\n",++ca);
for(int i = 0;i < m;++i){
sf("%d",&temp);pf("%lld\n",Query(temp));
}
}
return 0;
}

本文介绍了解决HDU 4825 Xor Query问题的一种方法,通过构建01字典树来快速查询与给定值X进行异或操作能得到的最大值。代码实现包括了字典树节点初始化、插入和查询等核心功能。
9万+

被折叠的 条评论
为什么被折叠?



