最大异或和

问题描述
给出n个整数,多组询问求一个给出的数与这n个数中的一个数的最大异或的值。
输入格式
第一行一个整数n,表示有个数字。
第二行n个正整数。
第三行一个整数m,表示m个询问。
第四行m个整数,表示m个询问的整数。
输出格式
共m行,对于每个询问输出最大的异或值。
输入样例
4
3 5 6 7
3
1 4 7
输出样例
7
7
4
样例说明
与1异或值最大的数为6,异或值为7
与4异或值最大的数为5,异或值为7
与7异或值最大的数为3,异或值为4
限制与约定
1<= n,m <=10^5,所有数据 < 2^31-1
时间限制:1s
空间限制:256MB

贪心异或,补齐到31位的思想非常好。
Code

#include<cstdio>
#include<iostream>
using namespace std;
int edge;
int son[4000005][2];
int pd[4000005];
int cc[4000005];
int n;
inline int read()
{
	char c=getchar();
	while(c<'0'||c>'9')c=getchar();
	int x=0;
	while(c>='0'&&c<='9')
	{
		x=x*10+c-'0';
		c=getchar();
	}
	return x;
}
inline void add(int x)
{
	int now=0;
	for(int i=31;i>=1;i--)
	{
		int u=((1<<(i-1))&x)>>(i-1);
		if(!son[now][u])
		{
			edge++;
			son[now][u]=edge;
		}
		now=son[now][u];
	}
	pd[now]=1;
	cc[now]=x;
}
inline int ask(int x)
{
	int maxx=-1;
	int now=0;
	for(int i=31;i>=1;i--)
	{
		int u=((1<<(i-1))&x)>>(i-1);
		if(son[now][!u])
		{
			now=son[now][!u];
			if(pd[now])
			{
			maxx=max(maxx,cc[now]^x);
			}
		}
		else
		{
			now=son[now][u];
			if(pd[now])
			{
			maxx=max(maxx,cc[now]^x);	
			}
		}
	}
	return maxx;
}
int main()
{
	n=read();
	for(int i=1;i<=n;i++)
	{
		add(read());
	}
	int m=read();
	for(int i=1;i<=m;i++)
	{
		printf("%d\n",ask(read()));
	}
	return 0;
}

### 关于最大异或问题的解决方案 对于最大异或问题,可以采用 Trie 树来解决这个问题。由于 `int` 类型在计算机中是以 32 位二进制表示(包括符号位),因此可以通过构建一个特殊的前缀树(Trie)来进行处理[^1]。 #### 构建 Trie 树 为了找到两个数最大异或,可以在 Trie 树上进行操作。具体来说: - 将每一个整数按照其二进制形式逐位插入到 Trie 树中; - 插入过程中优先考虑高位,在每一步尽可能选择与当前节点不同的分支,这样能使得最终计算出来的异或结果更大; ```cpp struct Node { int cnt; Node* next[2]; }; void insert(Node*& root, int num) { for(int i = 30; ~i; --i){ bool bit = ((num >> i) & 1); if(!root->next[bit]) root->next[bit] = new Node(); root = root->next[bit]; ++(root->cnt); } } ``` 这段代码展示了如何向 Trie 树中插入一个新的数。通过遍历该数的所有比特位并相应地更新指针指向的位置完成插入过程。 #### 查询最大异或 当需要查询某个特定数所能产生的最大异或时,则应尝试沿着 Trie 树走一条尽量使两者不同路径最多的路线。这通常意味着每当遇到分叉路口时总是挑选不同于目标数字对应位置上的那条支路。 ```cpp int query_max_xor(Node* root, int target) { int res = 0; for (int i = 30; ~i; --i) { bool wantBit = !((target >> i) & 1); // 希望这一位是啥 if (!root || !root->next[wantBit]) wantBit ^= 1; if(root && root->next[wantBit]){ res |= (wantBit << i); root = root->next[wantBit]; }else{ break; } } return res ^ target; } ``` 上述函数实现了对给定的目标 `target` 查找与其能够形成最大异或的过程。它会尽力选取那些可以使两者的差异最大的路径,并返回所获得的最大可能异或结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值