秋实大哥与快餐店(二进制+字典树)

秋实大哥与快餐店

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
 

朝为田舍郎,暮登天子堂。秋实大哥从小就怀抱有远大的理想,所以他开了一家快餐店。

秋实大哥根据菜的口感,给每一道菜一个唯一的 CID ,同时对于前来的客人,根据他们的口味喜好,秋实大哥会给每一个客人一个 PID

对于一个标号为 PID 的客人,他对标号为 CID 的菜的喜爱程度为 PIDCID ( 表示按位异或),该值越大表示越喜欢。

秋实大哥实在太忙了,现在他需要你来帮忙照看一下他的店铺。

Input

第一行包含一个整数 n ,表示秋实大哥的餐馆内现在有 n 道菜。

接下来一行包含 n 个整数,分别表示每一道菜的 CID

接下来一行包含一个整数 m ,表示接下来发生了 m 件事。

接下来的 m 行,每一行为以下两种事件之一:

0 c : 表示秋实大哥最新研制出一道标号为c的菜
1 p : 表示来了一位标号为p的客人,请你在已有的菜中找出一道他最喜爱的菜

1nm100000 0PIDCID1000000

Output

对于每一个 1   p 事件输出一个整数,表示该客人最喜欢的菜的标号。

Sample input and output

Sample Input Sample Output
1
1
3
1 1
0 2
1 1
1
2

Source

2015 UESTC Training for Data Structures


思路:

   因为题目说了是cid^pid最大的数,所以根据异或相同则0,不同则1的性质可知,只要是高位二进制各异就是最大的数了。所以我们可以用菜的价值来建立一颗
0-1的二叉树。


AC代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
#include<ctime>
#include<cstdlib>
#include<queue>
#include<vector>
#include<set>
using namespace std;
const int T=100100;
#define inf 0x3f3f3f3fL
#define mod 1000000000
typedef long long ll;
typedef unsigned long long ULL;

int n,m;
const int maxbit = 20;

struct node
{
	int L,R,id;
}tire[1<<22];

//其实就是一颗0-1组成的二叉树的叶子节点处标记一个菜品id

void Insert(int x)//插入一个数
{
	int rt = 1;
	for(int i=1;i<=maxbit;++i){//一共有20位
		if((x >>(maxbit - i))&1){//x当前二进制的maxbit-i+1位当前是否为1
			tire[rt].R = 1;//标记在右子树
			 rt=(rt<<1|1);
		}
		else {
			tire[rt].L = 1;//标记在左子树
			rt=(rt<<1);
		}
	}
	tire[rt].id = x;//放入菜品id
}

int query(int x)
{
	int rt = 1,tar = ~x;
	for(int i=1;i<=maxbit;++i){
		if((tar >>(maxbit-i))&1){//取反后的数在右子树
			if(tire[rt].R){//如果右子树标记过,则肯定是这个数最大
				rt = rt<<1|1;
			}
			else {//否则应该走回与x原来的二进制位才能继续找最大
				rt = rt << 1;
			}
		}
		else {
			if(tire[rt].L){
				rt = rt<<1;
			}
			else {
				rt = rt<<1|1;
			}
		}
	}
	return tire[rt].id;
}

int main()
{
#ifdef zsc 
	freopen("input.txt","r",stdin); 
#endif

	int i,j,k,c,p;

	while(~scanf("%d",&n))
	{
		memset(tire,0,sizeof(tire));
		for(i=0;i<n;++i){
			scanf("%d",&k);
			Insert(k);
		}
		scanf("%d",&m);
		for(i=0;i<m;++i){
			scanf("%d%d",&c,&p);
			if(c&1){
				printf("%d\n",query(p));
			}
			else {
				Insert(p);
			}
		}
	}

    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值