我们可以继续沿用running median中2个队列的好想法: 我们沿用2个堆栈。
光标前面的所有数都在栈A中,光标后的都在栈B中。栈A和栈B的栈顶分别是光标2边的2个数。因为问的位置保证在光标前,我们只要对于A数组维护一下前缀和。而光标的左右移动,我们就只要改变A,B栈顶的元素即可,插入也是同理。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1000005;
int Q;ll sum[maxn],f[maxn];int s[maxn];
struct node
{
int pos,val;
};
stack<node> a,b;
void work()
{
f[0]=-9999999999;
memset(s,0,sizeof(s));
while(!a.empty()) a.pop();
while(!b.empty()) b.pop();
int pos=0;
for(int qi=1;qi<=Q;qi++)
{
char ch;cin>>ch;int x;
if(ch=='I')
{
scanf("%d",&x);
node tmp;tmp.val=x;
if(!a.empty()) tmp.pos=a.top().pos+1;
else tmp.pos=1;
pos=tmp.pos;
a.push(tmp);s[pos]=x;
sum[pos]=sum[pos-1]+s[pos];f[pos]=max(f[pos-1],sum[pos]);
}
if(ch=='Q')
{
scanf("%d",&x);
printf("%lld\n",f[x]);
}
if(ch=='L')
{
if(!a.size()) continue;
node tmp=a.top();a.pop();b.push(tmp);
}
if(ch=='R')
{
if(!b.size()) continue;
node tmp=b.top();b.pop();
if(!a.empty()) tmp.pos=a.top().pos+1;
else tmp.pos=1;
s[tmp.pos]=tmp.val;
a.push(tmp);
sum[tmp.pos]=sum[tmp.pos-1]+s[tmp.pos];
f[tmp.pos]=max(f[tmp.pos-1],sum[tmp.pos]);
}
if(ch=='D')
{
a.pop();
}
}
}
int main()
{
while(scanf("%d",&Q)!=EOF)
{
work();
}
return 0;
}