HDU - 4825 Xor Sum(01字典树水题)

本文介绍了一种利用01字典树解决异或最大值问题的方法。通过建立字典树并采用贪心策略,实现对给定集合和询问集的有效处理,以找到使异或结果最大的数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Xor Sum

Zeus 和 Prometheus 做了一个游戏,Prometheus 给 Zeus 一个集合,集合中包含了N个正整数,随后 Prometheus 将向 Zeus 发起M次询问,每次询问中包含一个正整数 S ,之后 Zeus 需要在集合当中找出一个正整数 K ,使得 K 与 S 的异或结果最大。Prometheus 为了让 Zeus 看到人类的伟大,随即同意 Zeus 可以向人类求助。你能证明人类的智慧么? 

Input

输入包含若干组测试数据,每组测试数据包含若干行。 
输入的第一行是一个整数T(T < 10),表示共有T组数据。 
每组数据的第一行输入两个正整数N,M(<1=N,M<=100000),接下来一行,包含N个正整数,代表 Zeus 的获得的集合,之后M行,每行一个正整数S,代表 Prometheus 询问的正整数。所有正整数均不超过2^32。

Output

对于每组数据,首先需要输出单独一行”Case #?:”,其中问号处应填入当前的数据组数,组数从1开始计算。 
对于每个询问,输出一个正整数K,使得K与S异或值最大。

Sample Input

2
3 2
3 4 5
1
5
4 1
4 6 5 6
3

Sample Output

Case #1:
4
3
Case #2:
4

01字典树模版题。01字典树主要用于解决求异或最值的问题。然后贪心,有相反的走相反的,没有相反的才走相同的。

#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs (i << 1) + 1
#define INT(t) int t; scanf("%d",&t)

using namespace std;

const int maxn = 1e5 + 10;
LL color[maxn * 32];
int trie[maxn * 32][2];
int k = 1;

void add(LL x){
    int p = 0;
    for(int i = 32;i >= 0;-- i){
        int c = (x >> i) & 1;
        if(!trie[p][c])
            trie[p][c] = k ++;
        p = trie[p][c];
    }
    color[p] = x;
}

LL solve(LL x){
    int p = 0;
    for(int i = 32;i >= 0;-- i){
        int c = (x >> i) & 1;
        if(trie[p][c ^ 1])
            p = trie[p][c ^ 1];
        else p = trie[p][c];
    }
    return color[p];
}

int main() {
    int t;
    while(~scanf("%d",&t)){
        int cas = 1;
        while(t --){
            clr(trie,0); clr(color,0);
            k = 1;
            int n,m; scanf("%d%d",&n,&m);
            rep(i,0,n){
                LL a; scanf("%lld",&a);
                add(a);
            }
            printf("Case #%d:\n",cas ++);
            while(m --){
                LL x; scanf("%lld",&x);
                printf("%lld\n",solve(x));
            }
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值