Codeforce#430D.Vitya and Strange Lesson(01Trie)

本文介绍了一种使用01字典树解决特定异或查询问题的方法。通过构建01字典树并利用贪心策略,在每次查询中找到与给定值异或后不存在于数组中的最小数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

每次询问一个x,问数组中的数与x异或后,不存在的最小的数。

分析:

01字典树上贪心选择一下,选择的时候判断左孩子和右孩子满不满。每次询问的亦或值x只要一直累⊕就行

#include<bits/stdc++.h>
using namespace std;
#define N 300005
#define H 19
bool vis[N];
struct node
{
    node *nxt[2];
    int sz;
    node(){sz=0;nxt[0]=nxt[1]=NULL;}
};
void Insert(node *rt, int x)
{
    for(int i=H; i>=0; i--)
    {
        int id=(x>>i)&1;
        if(rt->nxt[id]==NULL) rt->nxt[id]=new node();
        rt=rt->nxt[id];
        rt->sz++;
    }
}
int getsz(node *p)
{
    if(p==NULL) return 0;
    return p->sz;
}
int query(node *rt, int X, int h)
{
    if(rt==NULL) return 0;
    if((X>>h)&1)
    {
        if(getsz(rt->nxt[1])!=(1<<h)) return query(rt->nxt[1], X, h-1);
        else return query(rt->nxt[0], X, h-1)+(1<<h);
    }
    else
    {
        if(getsz(rt->nxt[0])!=(1<<h)) return query(rt->nxt[0], X, h-1);
        else return query(rt->nxt[1], X, h-1)+(1<<h);
    }
}

void solve()
{
    node *rt=new node();
    int n, m, X=0;cin>>n>>m;
    for(int i=1; i<=n; i++)
    {
        int x;cin>>x;
        if(!vis[x]) Insert(rt, x), vis[x]=1;
    }
    while(m--)
    {
        int x;cin>>x;
        X^=x;
        cout << query(rt, X, H) << endl;
    }
}
int main()
{
    solve();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值