HDU 4825 Xor Sum(01字典树模板)

Xor Sum

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


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
 
查询的时候使用贪心的策略,当查询到第k位时,设当前二进制位表示的数字是x,那就走到x^1上,如果没有就继续向前走

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=1e5+7;
struct Node
{
	int id;
	Node *num[2];
	Node()
	{
		id=0;
		for(int i=0;i<2;i++)
		{
			num[i]=NULL;
		}
	}
};
int num[maxn];
char str[40];
void insert(Node *root,char *str,int index)
{
	Node *head=root;
	for(int i=0;i<=32;i++)
	{
		int tmp=str[i]-'0';
		if(head->num[tmp]==NULL)
		{
			head->num[tmp]=new Node;
		}
		head=head->num[tmp];
	}
	head->id=index;
	return;
}
int search(Node *root,char *str)
{
	Node *head=root;
	for(int i=0;i<=32;i++)
	{
		int tmp=str[i]-'0';
		if(head->num[tmp^1]) head=head->num[tmp^1];
		else head=head->num[tmp];
	}
	return head->id;
}
int main()
{
	int test;
	cin>>test;
	int cas=1;
	while(test--)
	{
		int n,m;
		scanf("%d%d",&n,&m);
		Node *root=new Node;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&num[i]);
			for(int j=0;j<=32;j++)
			{
				str[j]='0';
			}
			int tmp=num[i];
			int index=32;
			while(tmp)
			{
				if(tmp&1) str[index]='1';
				tmp>>=1;
				index--;
			}
			insert(root,str,i);
		}
		printf("Case #%d:\n",cas++);
		for(int i=0;i<m;i++)
		{
			int x;
			scanf("%d",&x);
			for(int i=0;i<=32;i++)
			{
				str[i]='0';
			}
			int index=32;
			int tmp=x;
			while(tmp)
			{
				if(tmp&1) str[index]='1';
				tmp>>=1;
				index--;
			}
			printf("%d\n",num[search(root,str)]);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37943488/article/details/81050199