HDU4825 Xor Sum(异或最值问题——01字典树)

171 篇文章 0 订阅
95 篇文章 0 订阅

Problem Link:http://acm.hdu.edu.cn/showproblem.php?pid=4825

Xor Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 132768/132768 K (Java/Others)
Total Submission(s): 6525    Accepted Submission(s): 2822

Problem Description

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

Source

2014年百度之星程序设计大赛 - 资格赛

 

思路:最大异或值问题,可通过01字典树在O(n)时间复杂度内解决。

 

AC code:

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn=100010;
int n,m;
LL x;
int a[maxn*32];
int ch[maxn*32][2];
int val[maxn*32];//以根节点到当前结点作为前缀的总个数
int sz;

void init()
{
	sz=1;
	memset(ch,0,sizeof(ch));
	memset(val,0,sizeof(val));
}

void _insert(LL x)
{
	int u=0;
	for(int i=32;i>=0;i--)
	{
		int c=(x>>i)&1;
		if(!ch[u][c])
		{
			ch[u][c]=sz++;
		}
		u=ch[u][c];
		val[u]++;
	}
}

void _delete(LL x)
{
	int u=0;
	for(int i=32;i>=0;i--)
	{
		int c=(x>>i)&1;
		u=ch[u][c];
		--val[u];
	}
}

LL query(LL x)//输出最大异或值res或与x异或结果最大的元素maxx 
{
	LL res=0;//输出最大异或值 
	LL maxx=0;//输出与x异或结果最大的元素maxx 
	int u=0;
	for(int i=32;i>=0;i--)
	{
		int c=(x>>i)&1;
		if(ch[u][c^1] && val[ch[u][c^1]])
		{
			res+=(1<<i);//第i位与x第i位不同,该位异或结果为1 
			maxx+=((c^1)<<i);//maxx第i位为((c^1)<<i)
			u=ch[u][c^1];
		}
		else
		{
			u=ch[u][c];
			maxx+=((c)<<i);//maxx第i位为((c)<<i)
		}
	}
	//return res;//输出最大异或值
	return maxx; 
}

int main()
{
	//freopen("D:\\in.txt","r",stdin);
	int T,cas;
	scanf("%d",&T);
	cas=0;
	while(T--)
	{
		cas++;
		scanf("%d%d",&n,&m);
		init();
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			_insert(a[i]);
		}
		printf("Case #%d:\n",cas);
		for(int i=1;i<=m;i++)
		{
			scanf("%lld",&x);
			LL ans= query(x);
			printf("%lld\n",ans);
		}
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林下的码路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值