Codeforces 842D Vitya and Strange Lesson【逆向思維+字典樹查詢亦或最小值】
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.
InputFirst 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
For each query print the answer on a separate line.
Examples input2 2 1 3 1 3output
1 0input
4 3 0 1 5 6 1 2 4output
2 0 0input
5 4 0 1 5 6 7 1 1 4 5output
2 2 0 2題目大意:
給出一個數組,每次操作將整個陣列亦或一個數x,問得到的陣列的結果中的mex.mex表示為自然數中第一個沒有出現過的數。
思路:
①首先我們知道,亦或x之後得到的陣列將其再亦或y值得的陣列,其實就是原陣列亦或(x^y)的結果。所以這裡我們沒有必要將原陣列進行變化。
②我們還知道,如果有:z^x=y,其中若x,y已知,那麼z是固定的。那麼我們可以根據這個特性,我們將問題翻轉一下。
我們將原陣列中不存在的數入樹。那麼對於每一個查詢temp,其實就相當於我們在樹上找一個值,使得這個值亦或temp最小。
引入了這個逆向思維之後,我們就變成了貪心find。
③過程維護一下即可。注意入樹的數值範圍。
Ac程式碼:
#include<stdio.h>
#include<string.h>
#include<map>
#include<algorithm>
#include<math.h>
#include<stdlib.h>
using namespace std;
#define ll long long int
#define maxn 2
typedef struct tree
{
tree *nex[maxn];
ll v;
ll val;
} tree;
tree root;
void init()
{
for(ll i=0; i<maxn; i++)
{
root.nex[i]=NULL;
root.v=0;
root.val=0;
}
}
void creat(char *str,int va)
{
int len=strlen(str);
tree *p=&root,*q;
for(int i=0; i<len; i++)
{
int id=str[i]-'0';
if(p->nex[id]==NULL)
{
q=(tree *)malloc(sizeof(root));
q->v=1;
for(int j=0; j<2; j++)
{
q->nex[j]=NULL;
}
p->nex[id]=q;
}
else
{
p->nex[id]->v++;
}
p=p->nex[id];
if(i==len-1)
{
p->val=va;
}
}
}
void find(char *str,ll query)
{
ll len=strlen(str);
tree *p=&root;
for(ll i=0; i<len; i++)
{
ll id=str[i]-'0';
if(p->nex[id]!=NULL)
{
p=p->nex[id];
}
else p=p->nex[1-id];
if(p==NULL)return ;
}
printf("%lld\n",p->val^query);
}
int main()
{
ll n,q;
while(~scanf("%lld%lld",&n,&q))
{
init();
map<ll,ll>s;
for(ll i=1; i<=n; i++)
{
ll x;
scanf("%lld",&x);
if(s[x]==0)
{
s[x]=1;
}
}
for(ll i=0; i<=600000; i++)
{
if(s[i]==0)
{
char ss[25];
ll x=i;
ss[21]='\0';
for(int j=20; j>=0; j--)
{
if(x)
{
ss[j]=x%2+'0';
x/=2;
}
else
{
ss[j]='0';
}
}
creat(ss,i);
}
}
ll temp=0;
while(q--)
{
ll x;
scanf("%lld",&x);
temp^=x;
x=temp;
char ss[25];
ss[21]='\0';
for(int j=20; j>=0; j--)
{
if(x)
{
ss[j]=x%2+'0';
x/=2;
}
else
{
ss[j]='0';
}
}
find(ss,temp);
}
}
}