Xor Sum (字典树-- 数组 大?小?)

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

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年百度之星程序设计大赛 - 资格赛

Recommend
liuyiding

==数组大小 一定要开好 要不一会超时 一会re 还有 Memory Limit ==

#include"iostream"
#include"cstring"
typedef long long int ll;
using namespace std;
const ll maxn = 3e6 + 9;
// dictionaries 字典 
ll cnt = 0;
ll node[maxn][3];
void innit()
{
	cnt = 0;
	memset(node, 0, sizeof(node));
}
void insert(ll s)
{
	ll p = 0;
	for (int i = 31; i >= 0; i--)
	{
		int c = (s >> i) & 1;
		if (!node[p][c]) node[p][c] = ++cnt;
		p = node[p][c];
	}
	//exist[p] = true;
}

ll solve(ll n) {
	ll p = 0, ans = 0;
	for (int i = 31; i >= 0; i--)
	{
		bool c = (n >> i) & 1;
		if (node[p][!c])
		{
			ans += !c << i;
			p = node[p][!c];
		}
		else
		{
			ans += c << i;
			p = node[p][c];
		}

	}
	return ans;
}
int main() {
	ll a;
	cin >> a;
	for (int j = 0; j < a; j++)
	{
		cout << "Case #" << j + 1 << ":" << endl;
		ll b, n;
		scanf("%lld%lld", &b, &n);
		innit();
		ll c;
		for (int i = 0; i < b; i++)
		{

			scanf("%lld", &c);
			insert(c);
		}
		for (int i = 0; i < n; i++)
		{
			scanf("%lld", &c);
			printf("%lld\n", solve(c));
		}
	}
}
发布了49 篇原创文章 · 获赞 0 · 访问量 660

猜你喜欢

转载自blog.csdn.net/qq_14989799/article/details/105325103