bzoj1503: [NOI2004]郁闷的出纳员
1503: [NOI2004]郁闷的出纳员
Time Limit: 5 Sec Memory Limit: 64 MB
Description
Input
Output
Sample Input
I 60
I 70
S 50
F 2
I 30
S 15
A 5
F 1
F 2
Sample Output
20
-1
2
HINT
Source
思路(copy):
首先,因为增加和减小是对所有元素而言,因此这个值我们不插入而是单独保存,设这个值为det。
那么插入一个元素x,我们插入x-det,这样保持插入的所有元素的真实值都是其加上det。
然后,每次减小时,我们需要进行删除,那么插入一个Min-det的节点,并将其调整到根节点,然后左子树就是被删除的。
之后,将根节点的右节点变为根节点。
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 struct data{ 5 int l,r,f,s,v,num; 6 }tr[100001]; 7 int n,m,l,tot,root,delta; 8 void pushup(int x){tr[x].s=tr[tr[x].l].s+tr[tr[x].r].s+1;} 9 void zig(int &x) 10 { 11 int y=tr[x].f; 12 int z=tr[y].f; 13 if(y==tr[z].l)tr[z].l=x; 14 else tr[z].r=x; 15 tr[x].f=z; 16 tr[y].l=tr[x].r; 17 tr[tr[x].r].f=y; 18 tr[x].r=y; 19 tr[y].f=x; 20 pushup(y); pushup(x); 21 if(y==root)root=x; 22 } 23 void zag(int &x) 24 { 25 int y=tr[x].f; 26 int z=tr[y].f; 27 if(y==tr[z].l)tr[z].l=x; 28 else tr[z].r=x; 29 tr[x].f=z; 30 tr[y].r=tr[x].l; 31 tr[tr[x].l].f=y; 32 tr[y].f=x; 33 tr[x].l=y; 34 pushup(y); pushup(x); 35 if(y==root)root=x; 36 } 37 void splay(int &x,int d) 38 { 39 while(tr[x].f!=d) 40 { 41 if(tr[tr[x].f].l==x)zig(x); 42 else zag(x); 43 } 44 } 45 void insert(int k) 46 { 47 if(!root) 48 { 49 root=++tot; 50 tr[tot].num=k; 51 tr[tot].s=1; 52 return; 53 } 54 int p=root,z; 55 while(p) 56 { 57 z=p; 58 ++tr[p].s; 59 if(k<tr[p].num)p=tr[p].l; 60 else p=tr[p].r; 61 } 62 if(tr[z].num>k)tr[z].l=++tot; 63 else tr[z].r=++tot; 64 tr[tot].num=k;tr[tot].s=1;tr[tot].f=z; 65 splay(tot,0); 66 } 67 int find(int x,int k) 68 { 69 if(k<=tr[tr[x].r].s)return find(tr[x].r,k); 70 if(k==tr[tr[x].r].s+1)return tr[x].num; 71 return find(tr[x].l,k-tr[tr[x].r].s-1); 72 } 73 int dec(int &x,int f) 74 { 75 if(!x)return 0; 76 int k; 77 if(tr[x].num+delta<m) 78 { 79 k=dec(tr[x].r,x)+tr[tr[x].l].s+1; 80 tr[tr[x].r].s=tr[x].s-k; 81 x=tr[x].r;tr[x].f=f; 82 } 83 else 84 { 85 k=dec(tr[x].l,x); 86 tr[x].s-=k; 87 } 88 return k; 89 } 90 int main() 91 { 92 scanf("%d%d",&n,&m); 93 while(n--) 94 { 95 char c[1]; 96 int k; 97 scanf("%s%d",&c,&k); 98 if(c[0]=='I'&&k>=m)insert(k-delta); 99 if(c[0]=='F')printf("%d\n",k<=tr[root].s?find(root,k)+delta:-1); 100 if(c[0]=='A')delta+=k; 101 if(c[0]=='S'){delta-=k;l+=dec(root,0);} 102 } 103 printf("%d\n",l); 104 return 0; 105 }