您的位置:首页 > 其它

hdu 4825 Xor Sum

2015-10-03 15:13 162 查看
题意:

给你n个数,然后给你m组询问,每组询问给你一个数,输出n个数中与该数亦或的最大的那个数,输出的是被亦或的那个数,不是亦或后的结果。

思路:

我用的是字典树+贪心,首先我们可以把前n个数拆成2进制,然后补全前导0,我是补成了34位,然后把他存在字典树中,对于每个询问,把他变成二进制,然后补全前导0,在字典树上查找,查找的时候用贪心的思想,因为前面的是高位,所以优先走不相等的,不行再走相等的那个,反正都是34位,怎么走都有路,一直找到最后.在每一位上ans+=
当前这一位的权值,每次ans<<=1,然后return ans.

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
using namespace std;
const int maxn = 200005;
struct tree
{
int id;         //最后一次经过此结点的商品ID
int num;            //记录包含该结点的单词个数
tree *next[2];
}*root;

char s[55];
void creat(char s[])
{
int len = strlen(s);
tree *p = root,*q;
for(int i = 0; i < len; i++)
{
int x = s[i] - '0';
if(p->next[x] == NULL)
{
q = (tree*)malloc(sizeof(tree));
//q->num = 0;
// q->id = -1;
for(int j = 0; j < 2; j++)
q->next[j] = NULL;
p->next[x] = q;
}
p = p->next[x];
}
//p->num = 1;
//p->id = k;
}
int Find(char s[],int k)
{
int ans = 0;
int len = strlen(s);
tree *p = root;
for(int i = 0; i < len; i++)
{
ans <<= 1;
int x = s[i] - '0';
x = 1 - x;
if(p->next[x])
{
p = p->next[x];
ans += x;
}
else
{
p = p->next[1-x];
ans += 1-x;
}
}
return ans;
}
void del(tree *root)
{
for(int i = 0; i < 2; i++)
{
if(root->next[i])
del(root->next[i]);
}
free(root);
}
void get_str(int x)
{
int t = 34;
s[t] = '\0';
while(t-- && x)
{
s[t] = (x&1) + '0';
x >>= 1;
}
for(int i = t; i >= 0; i--)
s[i] = '0';
}
int main()
{
int n,m,t,c = 1,x;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
root=(tree *)malloc(sizeof(tree));
for(int i = 0; i < 2; i++)
root->next[i] = NULL;
//root->num = 0;
//root->id = -1;
for(int i=0; i<n; i++)
{
scanf("%d",&x);
get_str(x);
creat(s);
}
printf("Case #%d:\n",c++);
for(int i = 0; i < m; i++)
{
scanf("%d",&x);
get_str(x);
printf("%d\n",Find(s,i));
}
del(root);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: