【NOIP2016提高A组模拟9.14】数列编辑器

题面

Description

在这里插入图片描述

Input

在这里插入图片描述

Output

在这里插入图片描述

Sample Input

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

Sample Output

2
3
样例解释:
在这里插入图片描述

Data Constraint

在这里插入图片描述

思路

这题可以考虑用链表来做,但这里讲的是另一种稍简单的方法。
首先,我们要明确最大前缀和的意思,如图:

数值前缀和最大前缀和
-1-1-1
211
-3-21
533

想必看了这个表格都知道最大前缀和是什么了吧。
介绍一下这题我的方法,用两个栈,左栈储存光标左边的数,右栈储存光标右边的数, s i s_i si表示左栈中前 i i i 个数的和, m a x n i maxn_i maxni表示第 i i i个数的最大前缀。左移即将左栈栈顶元素弹出,压入右栈栈顶,添加就将元素压入左栈栈顶,删除即删除左栈栈顶元素。最后右移即将右栈栈顶元素弹出,压入左栈栈顶,需要注意的是,在左栈顶元素压入时顺带更新 s s s数组与 m a x n maxn maxn数组。查询即输出 m a x n k maxn_k maxnk

Code

#include<cstdio>
#define max(a,b) ((a)>(b)?(a):(b))
#define N 1000005
int Q,q1[N],tp1,q2[N],tp2,s[N],maxn[N];
int main()
{
	freopen("editor.in","r",stdin);
	freopen("editor.out","w",stdout);
	scanf("%d",&Q);
	for(int i=0;i<=1000000;i++)
		maxn[i]=-9999999;
	for(int i=1;i<=Q;i++)
	{
		char ch;
		int x;
		ch=getchar();
		while(ch!='I'&&ch!='Q'&&ch!='L'&&ch!='R'&&ch!='D')
			ch=getchar(); 
		if(ch=='I')
		{
			scanf("%d",&x);
			q1[++tp1]=x;
			s[tp1]=s[tp1-1]+x;
			maxn[tp1]=max(maxn[tp1-1],s[tp1]);
		}
		else if(ch=='Q')
		{
			scanf("%d",&x);
			printf("%d\n",maxn[x]); 
		}
		else if(ch=='L')
		{
			if(!tp1) continue;
			tp1--;
			q2[++tp2]=q1[tp1+1];
		}
		else if(ch=='D') tp1--;
		else
		{
			if(!tp2) continue;
			tp2--;
			q1[++tp1]=q2[tp2+1];
			s[tp1]=s[tp1-1]+q1[tp1];
			maxn[tp1]=max(maxn[tp1-1],s[tp1]);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值