HDU--4825 Xor Sum(字典树)

题目传送门
题面
初识字典树,入门第一题。
题目大意:给你一些n个数,然后m次查询,每次查询都有输入一个数x,让你输出最开始给你的n个数中,与x异或最大的数。
思路
题意很简单,暴力也很舒服,但是,数据量不小,所以n^2的复杂度肯定是过不去的了。
字典树的查询应该是logn,首先,用字典树建树的时候,把他们分解成二进制建树,然后既然让我们找异或最大值,那我们就尽量去找和要查询的x的当前数位不同的。
AC

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
const int N=100000+10;
int tree[32*N][2];
int val[32*N];
int num;
void build(int a)
{
    int u=0;
    for(int i=31;i>=0;i--)
    {
        int c=(a>>i)&1;
        if(!tree[u][c])
        {
            tree[u][c]=num++;
        }
        u=tree[u][c];
    }
    val[u]=a;
}
int slary(int a)
{
    int u=0;
    for(int i=31;i>=0;i--)
    {
        int c=(a>>i)&1;
        if(tree[u][c^1])
        {
            u=tree[u][c^1];
        }
        else
        {
            u=tree[u][c];
        }
    }
    return val[u];
}
int n,m;
int main()
{
    int t;
    int q=1;
    scanf("%d",&t);
    while(t--)
    {    int x;
    memset(tree,0,sizeof(tree));
    memset(val,0,sizeof(val));
    num=1;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {

            scanf("%d",&x);
            build(x);
        }
        printf("Case #%d:\n",q++);
        while(m--)
        {
            scanf("%d",&x);
            printf("%d\n",slary(x));
        }
    }
    return 0;
}
发布了42 篇原创文章 · 获赞 5 · 访问量 931

猜你喜欢

转载自blog.csdn.net/qq_43402296/article/details/103886144