Educational Codeforces Round 23 E. Choosing The Commander(01Trie)

题意:三个操作:1增加一个数,2删除一个数,3求所有数^k<l的个数


思路:01Trie,求^k<l的个数时,如果l为1则加上0的,并往1走,如果l为0,就往0走。


代码:

#include<bits/stdc++.h>
using namespace std;
const int maxnode = 1e5*32+5;
int ch[maxnode][2], val[maxnode], sz;

void init()
{
    sz = 1;
    memset(ch[0], 0, sizeof(ch[0]));
}

void Insert(int x)
{
    int u = 0;
    for(int i = 31; i >= 0; i--)
    {
        int idx = (x>>i)&1;
        if(!ch[u][idx])
        {
            memset(ch[sz], 0, sizeof(ch[sz]));
            val[sz] = 0;
            ch[u][idx] = sz++;
        }
        u = ch[u][idx];
        val[u]++;
    }
}

void Delete(int x)
{
    int u = 0;
    for(int i = 31; i >= 0; i--)
    {
        int idx = (x>>i)&1;
        u = ch[u][idx];
        val[u]--;
    }
}

int Match(int x, int y)
{
    int u = 0, ans = 0;
    for(int i = 31; i >= 0; i--)
    {
        int idxx = (x>>i)&1;
        int idxy = (y>>i)&1;
        if(!idxy)
        {
            if(!ch[u][idxx]) break;
            u = ch[u][idxx];
        }
        else
        {
            if(ch[u][idxx]) ans += val[ch[u][idxx]];
            if(!ch[u][!idxx]) break;
            u = ch[u][!idxx];
        }
    }
    return ans;
}

int main(void)
{
    int q;
    while(cin >> q)
    {
        init();
        while(q--)
        {
            int cmd, x, y;
            scanf("%d%d", &cmd, &x);
            if(cmd == 1) Insert(x);
            else if(cmd == 2) Delete(x);
            else
            {
                scanf("%d", &y);
                printf("%d\n", Match(x, y));
            }
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值