842D - Vitya and Strange Lesson(01字典树+逆向思维)

题意:

就是给定N个数字,然后对于M个询问的K,求N个数字与K异或后得到的新数列的mex,就是在数字集合中未出现过的最小的非负数。

 

分析:

逆向思维:问题转化为求不在这N个数中的数与K异或值最小的那个数,这样将不在这N个数中的数插入到字典树中,然后就可以通过在字典树上查询与K异或值最小的元素即可、

注意:字典树的数据量应该为题目数据量的两倍,这样就有比所有原数据高一位的数据,这些数是可能构成最小值的

 

 AC代码:

 

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
using namespace std;

//注意manx为题目数据量的2倍,因为这样就能有一半数据是比原数据高1位
const int maxn = 600000 + 5;        //集合中的数字个数
int ch[20 * maxn][2];               //节点的边信息
int value[20 * maxn];                //节点存储的值
int node_cnt;                       //树中当前节点个数
bool tag[maxn];

void init()
{
    //树清空
    node_cnt = 1;
    memset(ch[0],0,sizeof(ch));
}
void Insert(int x)
{
    //在字典树中插入 X
    //和一般字典树的操作相同 将X的二进制插入到字典树中
    int cur = 0;
    for(int i = 20;i >= 0;--i)
    {
        int idx = (x >> i) & 1;
        if(!ch[cur][idx])
        {
            memset(ch[node_cnt],0,sizeof(ch[node_cnt]));
            ch[cur][idx] = node_cnt;
            value[node_cnt++] = 0;
        }
        cur = ch[cur][idx];
    }
    value[cur] = x;             //最后的节点插入value
}
int Query(int x)
{
    //在字典树中查找和X异或的最大值的元素Y 返回Y的值
    int cur = 0;
    for(int i = 20;i >= 0;--i)
    {
        int idx = (x >> i) & 1;
        if(ch[cur][idx]) cur = ch[cur][idx];
        else cur = ch[cur][idx ^ 1];
    }
    return value[cur];
}

int main()
{
    int n, m;
    scanf("%d%d", &n, &m);
    int x;
    for(int i = 0; i < n; ++i)
    {
        scanf("%d", &x);
        tag[x] = 1;
    }
    init();
    for(int i = 0; i <= 600001; ++i)
    {
        if(!tag[i]) Insert(i);
    }
    int re = 0;
    while(m--)
    {
        scanf("%d", &x);
        re ^= x;
        x =  re ^ Query(re);
        printf("%d\n", x);
    }
    return 0;
}

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值