题目:http://acm.hdu.edu.cn/showproblem.php?pid=4699
题意:
Editor
Time Limit: 3000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 2306 Accepted Submission(s): 704
Problem Description

Sample Input
8 I 2 I -1 I 1 Q 3 L D R Q 2
Sample Output
2 3HintThe following diagram shows the status of sequence after each instruction:![]()
Source
分析:用两个栈存数,光标始终在第一个栈的栈顶,左移s1就向s2里面弹一个数,右移s2就向s1里面弹一个值,插入和删除直接在s1的栈顶操作。找最大前缀和,可以用两个数组维护,一个记录前缀和,一个记录最大前缀和,当增加一个数,最大前缀和maxpre[k]只可能是maxpre[k-1]和pre[k]里面的最大值。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
using namespace std;
const int maxn = 1e6+7;
const int INF = 2E9;
int pre[maxn],maxpre[maxn],cur,x,q;
stack <int > s1,s2;
void Init()
{
maxpre[0]=pre[0]=-INF;
cur=1;
while(!s1.empty()) s1.pop();
while(!s2.empty()) s2.pop();
}
void Insert()
{
scanf("%d",&x);
s1.push(x);
pre[cur]=pre[cur-1]+x;
if(cur==1)
pre[cur]=x;
maxpre[cur]=max(maxpre[cur-1],pre[cur]);
cur++;
}
void Delete()
{
if(s1.empty())
return ;
s1.pop();
cur--;
}
void Lmove()
{
if(s1.empty())
return ;
int temp=s1.top();
s1.pop();
s2.push(temp);
cur--;
}
void Rmove()
{
if(s2.empty())
return ;
int temp=s2.top();
s2.pop();
s1.push(temp);
pre[cur]=pre[cur-1]+temp;
if(cur==1)
pre[cur]=temp;
maxpre[cur]=max(maxpre[cur-1],pre[cur]);
cur++;
}
void Query()
{
scanf("%d",&x);
printf("%d\n",maxpre[x]);
}
int main()
{
char str[3];
while(scanf("%d",&q)!=EOF)
{
Init();
while(q--)
{
scanf("%s",str);
switch(str[0])
{
case 'I':Insert();break;
case 'D':Delete();break;
case 'L':Lmove();break;
case 'R':Rmove();break;
case 'Q':Query();break;
default:break;
}
}
}
return 0;
}