您的位置:首页 > 其它

bzoj 1503: [NOI2004]郁闷的出纳员 splay

2016-07-27 12:03 507 查看
这题照别人的模板用splay写了好多次都没过,这次按自己的写法写了一遍,第一次TLE了,后来发现是旋转操作写错了,于是就A了!于是就A了!于是就A了!

这是本蒟蒻写过的第一道splay,有种莫名的小激动(求不喷)

代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define inf 0x7fffffff
#define N 100005
using namespace std;

int n,m,delta,ans,root,tot;
struct tree{int l,r,fa,k,s;}t
;

void rttl(int x)
{
int y=t[x].r;
if (x==root) root=y;
t[x].r=t[y].l;
t[t[y].l].fa=x;
t[y].l=x;
t[y].fa=t[x].fa;
if (x==t[t[x].fa].l) t[t[x].fa].l=y;
else t[t[x].fa].r=y;
t[x].fa=y;
t[x].s=t[t[x].l].s+t[t[x].r].s+1;
t[y].s=t[t[y].l].s+t[t[y].r].s+1;
}

void rttr(int x)
{
int y=t[x].l;
if (x==root) root=y;
t[x].l=t[y].r;
t[t[y].r].fa=x;
t[y].r=x;
t[y].fa=t[x].fa;
if (x==t[t[x].fa].l) t[t[x].fa].l=y;
else t[t[x].fa].r=y;
t[x].fa=y;
t[x].s=t[t[x].l].s+t[t[x].r].s+1;
t[y].s=t[t[y].l].s+t[t[y].r].s+1;
}

void splay(int x)
{
while (x!=root)
{
int f=t[x].fa;
if (f==root)
if (x==t[f].l) rttr(f);
else rttl(f);
else
{
int p=t[f].fa;
if (x==t[f].l)
{
if (f==t[p].l)
{
rttr(p);rttr(f);
}else
{
rttr(f);rttl(p);
}
}else
{
if (f==t[p].l)
{
rttl(f);rttr(p);
}else
{
rttl(p);rttl(f);
}
}
}
}
}

void insert(int k)
{
if (!root)
{
root=++tot;
t[tot].s=1;t[tot].k=k;
return;
}
int x=root,y;
while (x)
{
y=x;
t[x].s++;
if (k<t[x].k) x=t[x].l;
else x=t[x].r;
}
t[++tot].s=1;
t[tot].k=k;
t[tot].fa=y;
if (k<t[y].k) t[y].l=tot;
else t[y].r=tot;
splay(tot);
}

void del()
{
int x=root,y=0;
while (x)
if (t[x].k+delta<m) x=t[x].r;
else
{
y=x;
x=t[x].l;
}
if (!y)
{
ans+=t[root].s;
root=0;
}else
{
splay(y);
ans+=t[t[y].l].s;
t[y].l=0;
t[y].s=t[t[y].r].s+1;
}
}

int find(int k)
{
int x=root;
while (t[t[x].l].s+1!=k)
{
if (t[t[x].l].s+1<k)
{
k-=t[t[x].l].s+1;
x=t[x].r;
}else
{
x=t[x].l;
}
}
splay(x);
return t[x].k;
}

int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
{
char ch[2];
int x;
scanf("%s%d",ch,&x);
if (ch[0]=='I')
{
if (x>=m) insert(x-delta);
}else
if (ch[0]=='A')
{
delta+=x;
}else
if (ch[0]=='S')
{
delta-=x;
del();
}else
{
if (x==0||x>t[root].s) printf("%d\n",-1);
else printf("%d\n",find(t[root].s-x+1)+delta);
}
}
printf("%d\n",ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: