您的位置:首页 > 理论基础 > 数据结构算法

HDU4699Editor

2016-06-07 23:36 260 查看
题目描述:



Sample Input

8

I 2

I -1

I 1

Q 3

L

D

R

Q 2

Sample Output

2

3

Hint

The following diagram shows the status of sequence after each instruction:



题意:

对一个数列进行操作,I:光标位置后面插入一个权值为x的数,D:删除光标前的那个数,L:光标左移一位,R:光标右移一位,Q:求1到光标前位置的最大的前缀和。

题解:

此题因为是求光标前的k个数的前缀和最大值,比较容易处理。

此题可以用两个栈来模拟,一个栈记录光标前的数,一个栈记录光标后的数,用数组sum[size]=sum[size-1]+m;记录前缀和,用mmax[size]=max(mmax[size-1],sum[size]);记录光标前最大值。以下是ac代码:

#include<iostream>
#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
const int inf=0x3f3f3f3f;
int mmax[maxn],sum[maxn];
stack<int> s1;
stack<int> s2;
int main()
{
int n;
while(~scanf("%d",&n))
{
char s[5];
memset(mmax,0,sizeof(mmax));
memset(sum,0,sizeof(sum));
mmax[0]=-inf;                                   //没写这个wa了好多次!!!
int m;
int all=0,tmp,size=0;
while(!s1.empty())
s1.pop();
while(!s2.empty())
s2.pop();
while(n--)
{
scanf("%s",s);
switch(s[0])
{
case 'I':
scanf("%d",&m);
s1.push(m);
all++;
size=s1.size();
sum[size]=sum[size-1]+m;
mmax[size]=max(mmax[size-1],sum[size]);
break;
case 'D':
s1.pop();
all--;
break;
case 'L':
if(!s1.empty())
{
tmp=s1.top();
s1.pop();
s2.push(tmp);
}
break;
case 'R':
if(!s2.empty())
{
tmp=s2.top();
s2.pop();
s1.push(tmp);
size=s1.size();
sum[size]=sum[size-1]+tmp;
mmax[size]=max(mmax[size-1],sum[size]);
}
break;
case 'Q':
scanf("%d",&m);
printf("%d\n",mmax[m]);
break;
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构