Splay伸展树

来源:互联网 发布:java spring mvc 框架 编辑:程序博客网 时间:2024/05/16 12:15

查询一个数的前驱和后继


#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>#define N 100005#define inf 1<<29using namespace std;int pre[N],key[N],ch[N][2],root,tot1;  //分别表示父结点,键值,左右孩子(0为左孩子,1为右孩子),根结点,结点数量int n;//新建一个结点void NewNode(int &r,int father,int k){r=++tot1;pre[r]=father;key[r]=k;ch[r][0]=ch[r][1]=0;  //左右孩子为空}//旋转,kind为1为右旋,kind为0为左旋void Rotate(int x,int kind){int y=pre[x];//类似SBT,要把其中一个分支先给父节点ch[y][!kind]=ch[x][kind]; pre[ch[x][kind]]=y;//如果父节点不是根结点,则要和父节点的父节点连接起来if(pre[y])ch[pre[y]][ch[pre[y]][1]==y]=x;pre[x]=pre[y];ch[x][kind]=y;pre[y]=x;}//Splay调整,将根为r的子树调整为goalvoid Splay(int r,int goal){while(pre[r]!=goal){//父节点即是目标位置,goal为0表示,父节点就是根结点if(pre[pre[r]]==goal)Rotate(r,ch[pre[r]][0]==r);else{int y=pre[r];int kind=ch[pre[y]][0]==y;//两个方向不同,则先左旋再右旋if(ch[y][kind]==r){Rotate(r,!kind);Rotate(r,kind);}//两个方向相同,相同方向连续两次else{Rotate(y,kind);Rotate(r,kind);}}}//更新根结点if(goal==0) root=r;}int Insert(int k){int r=root;while(ch[r][key[r]<k]){//不重复插入if(key[r]==k){Splay(r,0);return 0;}r=ch[r][key[r]<k];}NewNode(ch[r][k>key[r]],r,k);//将新插入的结点更新至根结点Splay(ch[r][k>key[r]],0);return 1;}//找前驱,即左子树的最右结点int get_pre(int x){int tmp=ch[x][0];if(tmp==0)  return inf;while(ch[tmp][1])tmp=ch[tmp][1];return key[x]-key[tmp];}//找后继,即右子树的最左结点int get_next(int x){int tmp=ch[x][1];if(tmp==0)  return inf;while(ch[tmp][0])tmp=ch[tmp][0];return key[tmp]-key[x];}int main(){while(scanf("%d",&n)!=EOF){root=tot1=0;int ans=0;for(int i=1;i<=n;i++){int num;if(scanf("%d",&num)==EOF) num=0;if(i==1){ans+=num;NewNode(root,0,num);continue;}if(Insert(num)==0) continue;int a=get_next(root);int b=get_pre(root);ans+=min(a,b);}printf("%d\n",ans);}return 0;}


0 0