hdu4699(堆+模拟)

23 篇文章 0 订阅
17 篇文章 0 订阅

Editor

Time Limit: 3000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 628    Accepted Submission(s): 237


Problem Description
 

Sample Input
  
  
8 I 2 I -1 I 1 Q 3 L D R Q 2
 

Sample Output
  
  
2 3
 
 
 
 
本题是个模拟题。我们只需动态模拟该题的过程即可。由于查询时是求从1到当前位置的起点为1的不间断的连续区间最大和,这就大大降低了题目的难度。
sum[i]为到i的累加和,dp[i]为到i的起点为1的不间断的连续区间最大和,我们可知dp[i]=max(sum[i],dp[i-1]).题目光标的位置只能左右移动,插入、删除操作都是在光标左右两边进行的,可以联想堆栈这种数据结构。分别用两个堆栈维护光标左右两边,然后模拟过程。
#include<iostream>
#include<stack>
#include<cstdio>
#include<cstring>
using namespace std;

const int NINF=-100000000;
const int MAXN=1000000+100;
stack<int>Left,Right;
int sum[MAXN];
int ans[MAXN];

inline int Max(int a,int b)
{
	return a<b?b:a;
}

int main()
{
	int n,num,tmp;
	char cmd[5];
	while(~scanf("%d",&n))
	{
		while(!Left.empty())Left.pop();
		while(!Right.empty())Right.pop();
		num=0;
		sum[num]=0;
		ans[num]=NINF;
		num++;

		while(n--)
		{
			scanf("%s",cmd);
			if(cmd[0]=='I')
			{
				scanf("%d",&tmp);
				Left.push(tmp);
				sum[num]=sum[num-1]+tmp;
				ans[num]=Max(ans[num-1],sum[num]);
				num++;
			}
			else if(cmd[0]=='D')
			{
				Left.pop();
				num--;
			}
			else if(cmd[0]=='L')
			{
				if(!Left.empty())
				{
					Right.push(Left.top());
					Left.pop();
					num--;
				}
			}
			else if(cmd[0]=='R')
			{
				if(!Right.empty())
				{
					Left.push(Right.top());
					Right.pop();
					tmp=Left.top();

					sum[num]=sum[num-1]+tmp;
				    ans[num]=Max(ans[num-1],sum[num]);
				   
					num++;
				}
			}
			else if(cmd[0]=='Q')
			{
				scanf("%d",&tmp);
				printf("%d\n",ans[tmp]);
			}
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值