nefu1248智力异或 字典树

智力异或

Problem:1248

Time Limit:2000ms

Memory Limit:65535K

Description


有一个数列包含n个正整数a[1]~a[n](1<=n<1e5,0<=a[i]<1e9),现在有q次操作(q<1e5),每次操作是以下两种操作中的一种:
      1、输入x,对这n个数分别异或x;
      2、输入x,求数列中的某个数与x异或的最大值(即从数组中找一个数,使其与x异或值最大);

Input


第一行为T,表示有T(T<=10)组数据,每组数据的第一行为n和q,表示这个数列长为n,q次操作。然后输入这n个数。接下来,每次操作输入一行两个数op(op为1或者2)和x(0<=x<1e9),op=1表示进行操作1,op=2表示进行操作2;

Output


每次进行操作2时,用一行输出最大的异或值;

Sample Input


1
4 3
6 7 5 4
1 3
2 4
2 5

Sample Output


3
3

Hint


Source


CJJ

异或是对应的每位相同为0,不同为1.

根据题意,我们会想到肯定要让x和每位都与他尽量不同的抑或比较好。

所以可以建立一颗字典树,先把整个数组都插入字典树。字典树的每个分叉就表示0,1的分界。

从高位到低位。这样我们就可以一层一层,一位一位的比较,每次走不同的那边就好了。

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e5+5;
struct node
{
    int son[2];
}tree[40*maxn];
int root,tot;
int newnode()
{
    tot++;
    tree[tot].son[0]=tree[tot].son[1]=-1;
    return tot;
}
void insert(int x)
{
    int now=root;
    for(int i=30;i>=0;i--)
    {
        int tmp=!!(x&(1<<i));                //控制在01之间
        if(tree[now].son[tmp]==-1)tree[now].son[tmp]=newnode();
        now=tree[now].son[tmp];
    }
}
int query(int x)
{
    int ans=0;
    int now=root;
    for(int i=30;i>=0;i--)
    {
        int tmp=!(x&(1<<i));
        if(tree[now].son[tmp]==-1)now=tree[now].son[tmp^1];
        else
        {
             ans+=(1<<i);
             now=tree[now].son[tmp];
        }
    }
    return ans;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
       tot=-1;
       root=newnode();
       int n,q;
       scanf("%d%d",&n,&q);
       for(int i=1;i<=n;i++)
       {
           int x;
           scanf("%d",&x);
           insert(x);
       }
       int y=0;
       while(q--)
       {
           int op;
           scanf("%d",&op);
           if(op==1)
           {
               int x;
               scanf("%d",&x);
               y^=x;

           }
           else
           {
               int x;
               scanf("%d",&x);
               printf("%d\n",query(x^y));
           }
       }
    }
    return 0;
}
<br /><span id="_xhe_temp" width="0" height="0"><br /></span>

猜你喜欢

转载自blog.csdn.net/mayuqing98/article/details/79193066