hdu 4699 Editor (巧用两个栈)

题目: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
 

分析:用两个栈存数,光标始终在第一个栈的栈顶,左移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;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值