CodeForces - 842D——G - Vitya and Strange Lesson(字典树)

CodeForces - 842D
题目
Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.

Vitya quickly understood all tasks of the teacher, but can you do the same?

You are given an array consisting of n non-negative integers, and m queries. Each query is characterized by one number x and consists of the following consecutive steps:

Perform the bitwise addition operation modulo 2 (xor) of each array element with the number x.
Find mex of the resulting array.
Note that after each query the array changes.

Input
First line contains two integer numbers n and m (1 ≤ n, m ≤ 3·105) — number of elements in array and number of queries.

Next line contains n integer numbers ai (0 ≤ ai ≤ 3·105) — elements of then array.

Each of next m lines contains query — one integer number x (0 ≤ x ≤ 3·105).

Output
For each query print the answer on a separate line.

Examples
Input
2 2
1 3
1
3
Output
1
0
Input
4 3
0 1 5 6
1
2
4
Output
2
0
0
Input
5 4
0 1 5 6 7
1
1
4
5
Output
2
2
0
2
题意
题意很简单,先给你n个数,然后有m次查询,每次查询有会输入一个数x,让这n个数先异或一下x,然后求这些数的最小mex();每次轮查询异或之后这n个数都会被改变。
思路

  1. (x^ y)^z=x ^(y ^z),那么这样的话,我们就可以不用改变原来数组里的值。
  2. 对于一个表达式x^y=z;那么如果y和z已经知道,那么x就被唯一确定了,这样的话,我们对没有出现过的数进行建树,那么然后找到最小的和所要异或的值的最小的,就是答案。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
using namespace std;
const int N=3*1e5+110;
int n,m;
int tree[30*N][2];
int num;
int a[3*N];
int val[30*N];
void build(int x)
{
    int u=0;
    for(int i=25;i>=0;i--)
    {
        int c=(x>>i)&1;
        if(!tree[u][c])
        {
            tree[u][c]=num++;
        }
        u=tree[u][c];
    }
    val[u]=x;
}
int fin(int x)
{
    int u=0;
    for(int i=25;i>=0;i--)
    {
        int c=(x>>i)&1;
        if(tree[u][c])
        {
            u=tree[u][c];
        }
        else
        {
            u=tree[u][c^1];
        }
    }
    return val[u];
}
int main()
{
    scanf("%d%d",&n,&m);
    num=1;
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d",&x);
        a[x]=1;
    }
    for(int i=0;i<=600000;i++)
    {
        if(!a[i])
        {
              build(i);
        }
    }
    int q=0;
    int w;
    while(m--)
    {
        scanf("%d",&w);
        q^=w;
        printf("%d\n",fin(q)^q);
    }
    return 0;
}
发布了42 篇原创文章 · 获赞 5 · 访问量 929

猜你喜欢

转载自blog.csdn.net/qq_43402296/article/details/103895787
今日推荐