HDU 4825 Xor Sum(01字典树 + 贪心)

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

就是求亦或最大。

思路:

就是把集合中的所有数转化成二进制,从最高位到最低位存入到 trie 树中。

我们已知给的 数。把这个数按位取反,在trie 树上从高位到低位依次匹配。如果匹配上就最好,不能匹配上就转化成相反数。

最后找到的值就是我们需要的。

#include <bits/stdc++.h>
#define mem(x,v) memset(x,v,sizeof(x)) 
#define go(i,a,b)  for (int i = a; i <= b; i++)
#define og(i,a,b)  for (int i = a; i >= b; i--)
using namespace std;
typedef long long LL;
const double EPS = 1e-10;
const int INF = 0x3f3f3f3f;
const int N = 3e6+10;
int Ac[N][3];
LL End[N];
int cnt;

void Insert(LL z){
	int now = 0;
	og(i,32,0){
		int id = (z & (1ll << i)) ? 1 : 0;
		if (!Ac[now][id]) Ac[now][id] = ++cnt;
		now = Ac[now][id];
	}
	End[now] = z;
}
LL Find(LL z){
	int now = 0;
	og(i,32,0){
		int id = (z & (1ll << i)) ? 0:1;
		if (!Ac[now][id]) id = id ^ 1;
		now = Ac[now][id];
	}
	return End[now];
}
int main(){
	int T; cin>>T;
	int num = 1;
	while(T--){
		int n,m;
		scanf("%d%d",&n,&m);
		cnt = 0;
		go(i,1,n){
			LL z;
			scanf("%I64d",&z);
			Insert(z);
		}
		printf("Case #%d:\n",num++);
		go(i,1,m){
			LL z;
			scanf("%I64d",&z);
			LL ans = Find(z);
			printf("%I64d\n",ans);
		}
		mem(Ac,0);
	}


	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值