您的位置:首页 > 其它

hdu 4699 Editor (巧用两个栈)

2015-09-22 14:50 489 查看
题目: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
3
Hint
The following diagram shows the status of sequence after each instruction:





Source

2013 Multi-University Training Contest 10



分析:用两个栈存数,光标始终在第一个栈的栈顶,左移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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: