普通平衡树

贡献者:游客53075130 类别:代码 时间:2018-10-17 22:38:15 收藏数:13 评分:1
返回上页 举报此文章
请选择举报理由:




收藏到我的文章 改错字
#include<bits/stdc++.h>
using namespace std;
inline int read()
{
int f=1,x=0;char ch;
while(!isdigit(ch)){ch=getchar();if(ch=='-')f=-1;}
while(isdigit(ch)){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
return f*x;
}
int N,root,tot;
const int maxn = 500050,inf = 2147483647;
struct Node{
int val,size,cnt,fa,ch[2];
}t[maxn];
inline void pushup(int o){t[o].size=t[t[o].ch[0]].size+t[t[o].ch[1]].size+t[o].cnt;}
void rotate(int x)
{
register int y=t[x].fa;
register int z=t[y].fa;
register int k=t[y].ch[1]==x;
t[z].ch[t[z].ch[1]==y]=x;t[x].fa=z;
t[y].ch[k]=t[x].ch[k^1];t[t[x].ch[k^1]].fa=y;
t[x].ch[k^1]=y;t[y].fa=x;
pushup(y);pushup(x);
}
void Splay(int x,int goal)
{
while(t[x].fa!=goal)
{
register int y=t[x].fa,z=t[y].fa;
if(z!=goal)
(t[z].ch[0]==y)^(t[y].ch[0]==x)?rotate(x):rotate(y);
rotate(x);
}
if(!goal)root=x;
}
void find(int x)
{
int u=root;
if(!u)return;
while(t[u].ch[x>t[u].val] && x!=t[u].val)
u=t[u].ch[x>t[u].val];
Splay(u,0);
}
void insert(int x)
{
int u=root,pre=0;
while(u && x!=t[u].val)
{
pre=u;
u=t[u].ch[x>t[u].val];
}
if(u)t[u].cnt++;
else
{
u=++tot;
if(pre)t[pre].ch[x>t[pre].val]=u;
t[u].cnt=t[u].size=1;
t[u].val=x;t[u].fa=pre;
t[u].ch[0]=t[u].ch[1]=0;
}
Splay(u,0);
}
int Next(int x,int op)
{
find(x);
int u=root;
if((t[u].val<x && !op) || (t[u].val>x && op))return u;
u=t[u].ch[op];
while(t[u].ch[op^1])u=t[u].ch[op^1];
return u;
}
void Delete(int x)
{
int pre=Next(x,0);
int suf=Next(x,1);
Splay(pre,0);Splay(pre,suf);
int del=t[suf].ch[0];
if(t[del].cnt>1)
{
t[del].cnt--;
Splay(del,0);
}
else
t[suf].ch[0]=0;
}
int rank(int x)
{
int u=root;
if(x>t[u].size)return 0;
while(1)
{
int y=t[u].ch[0];
if(x>t[y].size+t[u].cnt)
{
x-=t[y].size+t[u].cnt;
u=t[u].ch[1];
}
else
if(t[y].size>=x)
u=y;
else
return t[u].val;
}
}
int main()
{
N=read();
insert(inf);insert(-inf);
while(N--)
{
int op=read();
if(op==1)insert(read());
if(op==2)Delete(read());
if(op==3)
{
find(read());
printf("%d\n",t[t[root].ch[0]].size);
}
if(op==4)printf("%d\n",rank(read()+1));
if(op==5)printf("%d\n",t[Next(read(),0)].val);
if(op==6)printf("%d\n",t[Next(read(),1)].val);
}
return 0;
}
声明:以上文章均为用户自行添加,仅供打字交流使用,不代表本站观点,本站不承担任何法律责任,特此声明!如果有侵犯到您的权利,请及时联系我们删除。
文章热度:
文章难度:
文章质量:
说明:系统根据文章的热度、难度、质量自动认证,已认证的文章将参与打字排名!

本文打字排名TOP20

登录后可见

用户更多文章推荐