题面
Description
Input
Output
Sample Input
8
I 2
I -1
I 1
Q 3
L
D
R
Q 2
Sample Output
2
3
样例解释:
Data Constraint
思路
这题可以考虑用链表来做,但这里讲的是另一种稍简单的方法。
首先,我们要明确最大前缀和的意思,如图:
数值 | 前缀和 | 最大前缀和 |
---|---|---|
-1 | -1 | -1 |
2 | 1 | 1 |
-3 | -2 | 1 |
5 | 3 | 3 |
想必看了这个表格都知道最大前缀和是什么了吧。
介绍一下这题我的方法,用两个栈,左栈储存光标左边的数,右栈储存光标右边的数,
s
i
s_i
si表示左栈中前
i
i
i 个数的和,
m
a
x
n
i
maxn_i
maxni表示第
i
i
i个数的最大前缀。左移即将左栈栈顶元素弹出,压入右栈栈顶,添加就将元素压入左栈栈顶,删除即删除左栈栈顶元素。最后右移即将右栈栈顶元素弹出,压入左栈栈顶,需要注意的是,在左栈顶元素压入时顺带更新
s
s
s数组与
m
a
x
n
maxn
maxn数组。查询即输出
m
a
x
n
k
maxn_k
maxnk。
Code
#include<cstdio>
#define max(a,b) ((a)>(b)?(a):(b))
#define N 1000005
int Q,q1[N],tp1,q2[N],tp2,s[N],maxn[N];
int main()
{
freopen("editor.in","r",stdin);
freopen("editor.out","w",stdout);
scanf("%d",&Q);
for(int i=0;i<=1000000;i++)
maxn[i]=-9999999;
for(int i=1;i<=Q;i++)
{
char ch;
int x;
ch=getchar();
while(ch!='I'&&ch!='Q'&&ch!='L'&&ch!='R'&&ch!='D')
ch=getchar();
if(ch=='I')
{
scanf("%d",&x);
q1[++tp1]=x;
s[tp1]=s[tp1-1]+x;
maxn[tp1]=max(maxn[tp1-1],s[tp1]);
}
else if(ch=='Q')
{
scanf("%d",&x);
printf("%d\n",maxn[x]);
}
else if(ch=='L')
{
if(!tp1) continue;
tp1--;
q2[++tp2]=q1[tp1+1];
}
else if(ch=='D') tp1--;
else
{
if(!tp2) continue;
tp2--;
q1[++tp1]=q2[tp2+1];
s[tp1]=s[tp1-1]+q1[tp1];
maxn[tp1]=max(maxn[tp1-1],s[tp1]);
}
}
}