P3369 【模板】普通平衡树(Treap/SBT)

来源:互联网 发布:sizeof 数组 编辑:程序博客网 时间:2024/04/29 13:02

题目描述

您需要写一种数据结构(可参考题目标题),来维护一些数,其中需要提供以下操作:

  1. 插入x数

  2. 删除x数(若有多个相同的数,因只删除一个)

  3. 查询x数的排名(若有多个相同的数,因输出最小的排名)

  4. 查询排名为x的数

  5. 求x的前驱(前驱定义为小于x,且最大的数)

  6. 求x的后继(后继定义为大于x,且最小的数)

输入输出格式

输入格式:

第一行为n,表示操作的个数,下面n行每行有两个数opt和x,opt表示操作的序号(1<=opt<=6)

输出格式:

对于操作3,4,5,6每行输出一个数,表示对应答案

输入输出样例

输入样例#1:
101 1064654 11 3177211 4609291 6449851 841851 898516 819681 4927375 493598
输出样例#1:
10646584185492737

说明

时空限制:1000ms,128M

1.n的数据范围:n<=100000

2.每个数的数据范围:[-1e7,1e7]

来源:Tyvj1728 原名:普通平衡树

在此鸣谢


又是这题,哈哈,这次是splay。

宝宝根本看不懂哦(想哭)。

这次抄了一个奇奇怪怪的代码,以后应该是用不到了(无力改代码)。


#include<iostream>#include<cstdio>using namespace std;const int inf=1e9+7;const int N=100005;int n,cnt,root,ch[N][2],f[N],sz[N],w[N],key[N];int get(int x){return ch[f[x]][1]==x;}void update(int x){sz[x]=w[x]+sz[ch[x][0]]+sz[ch[x][1]];}void rotate(int x){int y=f[x],z=f[y],which=get(x);ch[y][which]=ch[x][which^1];f[ch[x][which^1]]=y;ch[x][which^1]=y;f[y]=x;f[x]=z;if(z)ch[z][ch[z][1]==y]=x;update(y);update(x);}void splay(int x){for(int fa;(fa=f[x]);rotate(x))if(f[fa])rotate(get(x)==get(fa)?fa:x);root=x;}void insert(int x){if(!root){root=++cnt;ch[root][0]=ch[root][1]=f[root]=0;key[root]=x,w[root]=1;return;}int now=root,fa=0;while(1){if(key[now]==x){w[now]++;update(now),update(fa);splay(now);return ;}fa=now,now=ch[now][x>key[now]];if(now==0){cnt++;ch[cnt][0]=ch[cnt][1]=0;sz[cnt]=w[cnt]=1;key[cnt]=x;f[cnt]=fa,ch[fa][x>key[fa]]=cnt;update(fa);splay(cnt);return ;}}}int ask_rank(int x){int ans=1,now=root;while(1){if(x<key[now])now=ch[now][0];else{ans+=sz[ch[now][0]];if(x==key[now]){splay(now);return ans;}ans+=w[now];now=ch[now][1];}}}int ask_num(int x){int now=root;while(1){if(ch[now][0]&&x<=sz[ch[now][0]])now=ch[now][0];else{int tmp=sz[ch[now][0]]+w[now];if(x<=tmp)return key[now];x-=tmp;now=ch[now][1];}}}int ask_pre(int x){int now=root,res=-inf;while(1){if(!now)break;if(key[now]<x){res=max(res,key[now]);now=ch[now][1];}elsenow=ch[now][0];}return res;}int ask_nxt(int x){int now=root,res=inf;while(1){if(!now)break;if(key[now]>x){res=min(res,key[now]);now=ch[now][0];}elsenow=ch[now][1];}return res;}void del(int x){ask_rank(x);if(w[root]>1){w[root]--;return ;}if(ch[root][0]*ch[root][1]==0){root=ch[root][0]+ch[root][1],f[root]=0;return ;}int lft=ch[root][0];while(ch[lft][1])lft=ch[lft][1];int old=root;splay(lft);f[ch[old][1]]=root;ch[root][1]=ch[old][1];update(root);}int main(){scanf("%d",&n);while(n--){int opt,x;scanf("%d%d",&opt,&x);switch(opt){case 1:insert(x);break;case 2:del(x);break;case 3:printf("%d\n",ask_rank(x));break;case 4:printf("%d\n",ask_num(x));break;case 5:printf("%d\n",ask_pre(x));break;case 6:printf("%d\n",ask_nxt(x));break;}}return 0;}


0 0
原创粉丝点击