ACdream群OJ 1063 字典树的运用

传送门:点击打开链接

平衡树

Time Limit: 4000/2000MS (Java/Others) Memory Limit: 128000/64000KB (Java/Others)
Problem Description
神奇的cxlove有一颗平衡树,其树之神奇无法用语言来描述 OrzOrz。 这棵树支持3种操作: 1、加入一个数到树中,维护平衡树的合法性; 2、给一个数X,用O(1)的时间求出来树中的数Y使得 Y ^ X 最大(异或操作, Pascal 写作 xor , 0 ^ 0 = 0 , 1 ^ 1 = 0 , 0 ^ 1 = 1 , 1 ^ 0 = 1 , 2 ^ 3 = 1) 3、给一个数X,用O(1)的时间求出来树中的数Y使得 Y ^ X 最小(异或操作, Pascal 写作 xor , 0 ^ 0 = 0 , 1 ^ 1 = 0 , 0 ^ 1 = 1 , 1 ^ 0 = 1 , 2 ^ 3 = 1) 请你帮忙实现这颗树。 cxlove由于过于牛,有些事情是无法做到的,你能在1s以内通过就好了。 最后补充一句,cxlove是世界冠军!
Input

第一行是数据组数T (T ≤ 100)

对于每组数据,第一行是操作数N (N ≤ 10000)

以下 行,每行一个字符串一个数字,分别代表:

  1. insert X ,加入数 X
  2. qmax X ,求第2种操作的答案
  3. qmin X ,求第3种操作的答案

输入保证不存在空树Query的情况 (1 ≤ X ≤ 1e9)

Output

对于操作 2 , 3 输出相应的答案。

Sample Input
1
4
insert 1
insert 2
qmin 1
qmax 1
Sample Output
0
3
Hint
Huge input and output. Please do not use: 1. cin ans cout of C++ 2. scanner of Java(Maybe BufferedReader is quicker)
Source
buaads
思路:按位建立字典树。从高位开始。
查询的时候,如果查询最大值,就尝试往和查询的这一位相反的方向走,查询最小值就尝试往和这位相同的方向走。
代码:
#include<cstdio>
#include<cstring>
int ch[1000005][2];
int cnt;
void insert(int x)
{
	int root = 1;
	for (int i = 30; i >= 0; i--)
	{
		bool tmp = 0;
		if (x & (1 << i)) tmp = 1;
		if (!ch[root][tmp]) ch[root][tmp] = ++cnt;
		root = ch[root][tmp];
	}
}
int quemax(int x)
{
	int root = 1, res = 0;
	for (int i = 30; i >= 0; i--)
	{
		bool tmp = 0;
		if (x & (1 << i)) tmp = 1;
		if (ch[root][!tmp])
		{
			root = ch[root][!tmp];
			res |= 1 << i;
		}
		else root = ch[root][tmp];
	}
	return res;
}
int quemin(int x)
{
	int root = 1, res = 0;
	for (int i = 30; i >= 0; i--)
	{
		bool tmp = 0;
		if (x & (1 << i)) tmp = 1;
		if (ch[root][tmp])
		{
			root = ch[root][tmp];
		}
		else
		{
			res |= 1 << i;
			root = ch[root][!tmp];
		}
	}
	return res;
}
int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		memset(ch, 0, sizeof(ch));
		cnt = 1;
		int n;
		scanf("%d", &n);
		while (n--)
		{
			char s[10];
			int x;
			scanf("%s %d", s, &x);
			if (s[0] == 'i') insert(x);
			else if (s[2] == 'a') printf("%d\n", quemax(x));
			else printf("%d\n", quemin(x));
		}
	}
	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值