uestc data structure n 秋实大哥与快餐店

0 篇文章 0 订阅

学到了一种新的数据结构——字典树

貌似用链表存是最好的办法

容易证明查询的时候尽量走与p不同的路能是p^c最大

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;

struct T{
	int c;
	T *left,*right;
};

void insert(int c,T* root,int dit){
	if(dit==-1){
		root->c=c;
		return ;
	}
	if((c&(1<<dit))==0){
		if(root->left==NULL){
			T *child=(T*)malloc(sizeof(T));
			child->right=child->left=NULL;
			child->c=-1;
			root->left=child;
			insert(c,child,dit-1);
		}
		else
			insert(c,root->left,dit-1);
	}
	else{
		if(root->right==NULL){
			T *child=(T*)malloc(sizeof(T));
			child->left=child->right=NULL;
			child->c=-1;
			root->right=child;
			insert(c,child,dit-1);
		}
		else
			insert(c,root->right,dit-1);
	}
}

void dfs(T* root){
//	cout<<(root->c)<<" "<<(root->left)<<root->right<<endl;
	if(root->left!=NULL)
		dfs(root->left);
	if(root->right!=NULL)
		dfs(root->right);
}

int query(int p,T* root,int dit){
	//cout<<root<<" "<<dit<<" "<<root->c<<endl;
	if(dit==-1){
		return root->c;
	}
	if((p&(1<<dit))==0){
		if(root->right==NULL){
			return query(p,root->left,dit-1);
		}
		else
			return query(p,root->right,dit-1);
	}
	else{
		if(root->left==NULL){
			return query(p,root->right,dit-1);
		}
		else
			return query(p,root->left,dit-1);
	}	
}

int main(){
	int n,m,type,c,p;
	cin>>n;
	T *root=(T*)malloc(sizeof(T));
	root->left=root->right=NULL;
	root->c=-1;
	while(n--){
		cin>>c;
		insert(c,root,19);
	}
//	dfs(root);
	cin>>m;
	while(m--){
		cin>>type;
		if(type==0){
			cin>>c;
			insert(c,root,19);
		}
		else{
			cin>>p;
			cout<<query(p,root,19)<<endl;
		}
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值