当前位置: 代码迷 >> 综合 >> 【HDU - 4825】 Xor Sum 【01 Trie -- 静态区间查询】
  详细解决方案

【HDU - 4825】 Xor Sum 【01 Trie -- 静态区间查询】

热度:81   发布时间:2023-11-10 03:04:33.0

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 Trie 树 用来求异或最大值很方便 。
我们将所有的数字化为二进制,然后就当成字符串存进去就行了。同时查询的时候用了贪心的策略,详细的看代码。
这个是静态的区间,查询,比较简单。

看代码

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int>pii;
#define first fi
#define second se
#define LL long long
#define fread() freopen("in.txt","r",stdin)
#define fwrite() freopen("out.txt","w",stdout)
#define CLOSE() ios_base::sync_with_stdio(false)const int MAXN = 100000+11;
const int MAXM = 1e6;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;struct Trie{int ch[MAXN*32][2],tot;LL val[MAXN*32];    void init(){memset(ch[0],0,sizeof(ch[0]));tot=1;}void Insert(LL a){int u=0;for(int i=31;i>=0;i--){int c=(1&(a>>i)) ;if(!ch[u][c]){memset(ch[tot],0,sizeof(ch[tot]));val[tot]=0;ch[u][c]=tot++;} u=ch[u][c];}  val[u]=a;//最后的二进制存原数} LL query(LL x){int u=0;for(int i=31;i>=0;i--){ // 这里一定要是 倒序插入,高位在上面,贪心需要int c=(1&(x>>i));if(ch[u][c^1]) u=ch[u][c^1]; // 如果c为0,那么异或的这一位,肯定是1最好。 如果c=1,那么异或的这一位,肯定是0最好。 c^1 就可以满足这样的需求。else u=ch[u][c]; }return val[u];}
}trie;
int main(){CLOSE();
// fread();
// fwrite();int T;scanf("%d",&T);int ncase=1;while(T--){int n,m;scanf("%d%d",&n,&m);trie.init();for(int i=1;i<=n;i++) {LL a;scanf("%lld",&a);trie.Insert(a);}printf("Case #%d:\n",ncase++);while(m--){LL a;scanf("%lld",&a);printf("%lld\n",trie.query(a));}} return 0;
}