CodeForces - 706D Vasiliy's Multiset(字典树删除操作)

题目链接:点击查看

题目大意:给出一个正整数n,初始时有一个multiset,接下来有n次操作,实现所有操作,对于每个操作,会有三种形式:

  1. + x:向集合中添加一个 x
  2. - x:从集合中删掉一个 x
  3. ? x:从集合中选出一个数k,使得 k xor x 的结果最大,输出这个结果

题目分析:因为需要让异或值最大,那么显然就是要用01字典树处理了,使用字典树遇到的问题是如何在字典树中删除掉一个数,其实并不麻烦,我们只需要在每个节点上多开一个val数组,用来记录每个节点被多少个数字所公用,若需要删除某个数值时,在树上遍历一遍这个数,让所经过的val都减一,如果遍历到某个节点,发现节点只有当前的数字所使用时,也就是val[node]=1,这个时候在将val数组减一之后,顺便将其父节点与当前节点的连边也删除掉,也就是让trie[pos][to]=0就好了,具体实现可以看代码,剩下的就是01字典树的模板题了

有一个小细节可以注意一下,为了加快代码的运行速度,字典树中完全可以只储存种类,开一个无序map储存个数即可,插入和删除的操作只发生在第一次添加某个数字以及最后一次删掉某个数字才会与字典树发生交互,剩下的改变都只是O(1)改变无序map中的值

代码:

#include<iostream>
#include<cstdio> 
#include<string>
#include<ctime>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cmath>
#include<sstream>
#include<unordered_map>
using namespace std;

typedef long long LL;

const int inf=0x3f3f3f3f;

const int N=2e5+100;

int trie[N*35][2],val[N*35],cnt;//val记录每个节点被遍历过多少次 

unordered_map<int,int>mp;

void insert(int x)
{
	int pos=0;
	for(int i=31;i>=0;i--)
	{
		int to=(x>>i)&1;
		if(!trie[pos][to])
			trie[pos][to]=++cnt;
		pos=trie[pos][to];
		val[pos]++;
	}
}

void erase(int x)
{
	int pos=0;
	for(int i=31;i>=0;i--)
	{
		int to=(x>>i)&1;
		int ppos=pos;//储存一下父节点
		pos=trie[pos][to];
		val[pos]--;
		if(!val[pos])//如果后续节点空出来了,则删掉父节点-当前节点这条边
			trie[ppos][to]=0;
	}
}

int serach(int x)
{
	int pos=0,ans=0;
	for(int i=31;i>=0;i--)
	{
		int to=(x>>i)&1;
		if(trie[pos][!to])
		{
			pos=trie[pos][!to];
			ans|=(1<<i);
		}
		else
			pos=trie[pos][to];
	}
	return ans;
} 

int main()
{
//	freopen("input.txt","r",stdin);
//	ios::sync_with_stdio(false);
	int n;
	scanf("%d",&n);
	insert(0);
	while(n--)
	{
		char s[5];
		int num;
		scanf("%s%d",s,&num);
		if(s[0]=='+')
		{
			if(!mp[num])
				insert(num);
			mp[num]++;
		}
		else if(s[0]=='-')
		{
			mp[num]--;
			if(!mp[num])
				erase(num);
		}
		else
		{
			printf("%d\n",serach(num));
		}
	}

	
	
	
	
	
	
	
	
	
	return 0;
}
发布了549 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/104043800
今日推荐