Editor HDU - 4699 (栈)

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:

题意:n个操作

5种操作,I x:该光标位置插入x并且光标后移

     D :删除光标前的一个数

     L :光标左移

    R :光标右移

    Q k:询问位置k之前的最大前缀和,k不会超过当前光标的位置

思路:

因为 I、D、L、R四种操作都时对于光标处发生,而且光标都只会移动一个位置,所以使用一种线性结构储存序列。可用数组、栈、双端队列。

这里使用两个栈进行序列的维护。

因为询问位置k之前的最大前缀和,那我们肯定要知道其前缀和才能得到最大的前缀和,所以用sum记录前缀和,ans【pos】 = max(ans【pos-1】,sum【pos】)

注:判断栈是否为空

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e6+6;
int n;
int sum[maxn];
int ans[maxn];
stack<int>s1,s2;
int main()
{
    while(~scanf("%d",&n))
    {
        int pos = 0;
        ans[0] = -0x3f3f3f3f;
        while(!s1.empty())s1.pop();
        while(!s2.empty())s2.pop();
        while(n--)
        {
            char c;
            int x;
            scanf(" %c",&c);
            if(c == 'I')
            {
                scanf("%d",&x);
                s1.push(x);
                pos++;
                sum[pos] = sum[pos-1] + x;
                ans[pos] = max(ans[pos-1],sum[pos]);
            }
            else if(c == 'D' && !s1.empty())
            {
                s1.pop();
                pos--;
            }
            else if(c == 'L' && !s1.empty())
            {
                s2.push(s1.top());
                s1.pop();
                pos--;
            }
            else if(c == 'R' && !s2.empty())
            {
                s1.push(s2.top());
                s2.pop();
                pos++;
                sum[pos] = sum[pos-1] + s1.top();
                ans[pos] = max(sum[pos],ans[pos-1]);
            }
            else if(c == 'Q')
            {
                scanf("%d",&x);
                printf("%d\n",ans[x]);
            }
        }
    }
}
View Code

猜你喜欢

转载自www.cnblogs.com/iwannabe/p/10631813.html