ACdream OJ 1063 平衡树

【题意】点击打开链接

【解题方法】水题,字典树XOR搞一搞就好了。

【AC 代码】

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=1e6+2;
struct node{
    int ch[maxn][2];
    int root,L;
    int newnode(){
        ch[L][0]=ch[L][1]=-1;
        return L++;
    }
    void init(){
        L=0;
        root=newnode();
    }
    void Insert(int x){
        int now=root;
        for(int j=30; j>=0; j--){
            int go=(x&(1<<j))?1:0;
            if(ch[now][go]==-1){
                ch[now][go]=newnode();
                now=ch[now][go];
            }else
                now=ch[now][go];
        }
    }
    int querymax(int x){
        int now=root;
        int ans=0;
        for(int j=30; j>=0; j--){
            int go=(x&(1<<j))?1:0;
            if(ch[now][!go]!=-1){
                ans|=(1<<j),now=ch[now][!go];
            }else{
                now=ch[now][go];
            }
        }
        return ans;
    }
    int querymin(int x)
    {
        int now=root;
        int ans=0;
        for(int j=30; j>=0; j--){
            int go=(x&(1<<j))?1:0;
            if(ch[now][go]!=-1){
                now=ch[now][go];
            }else{
                ans|=(1<<j);
                now=ch[now][!go];
            }
        }
        return ans;
    }
}Trie;
int main()
{
    int T,n;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        char op[10];
        int x;
        Trie.init();
        while(n--){
            scanf("%s",op);
            scanf("%d",&x);
            if(strcmp(op,"insert")==0){
                Trie.Insert(x);
            }else if(strcmp(op,"qmin")==0){
                printf("%d\n",Trie.querymin(x));
            }else{
                printf("%d\n",Trie.querymax(x));
            }
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值