HDU 4699 Editor (对顶栈)

Editor

时间限制: 1 Sec  内存限制: 128 MB
提交: 8  解决: 5
[提交] [状态] [讨论版] [命题人:admin]

题目描述

You are going to implement the most powerful editor for integer sequences.
The sequence is empty when the editor is initialized.
There are 5 types of instructions.

I x Insert x after the cursor.
D Delete the element before the cursor.
L Move the cursor left unless it has already been at the begin.
R Move the cursor right unless it has already been at the end.
Q k Suppose that the current sequence BEFORE the cursor is {a1,a2,...,an}.Find max1≤i≤k Si where Si=a1+a2+...+ai.

 

输入

The input file consists of multiple test cases.For eache test case:
The first line contains an integer Q,which is the number of instructions.The next Q lines contain an instruction as described above。
(1≤Q≤106,|x|≤103 for I instruction,1≤k≤n for Q instruction)

 

输出

For eache Q instruction,output the desired value.

 

样例输入

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

 

样例输出

2
3

 

提示

The following diagram shows the status of sequence after each instruction: 

 
思路:
 
根据题意要求实现对顶栈,同时更新光标前的栈的最大值。
 
代码如下:
#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e6 + 10;
stack<int> before, after;
int sum = 0, f[maxn], n, x, pn;
char op[2];

int main() {
    scanf("%d", &n);
    f[0]=-0x3f3f3f3f,sum=0;
    while (n--) {
        scanf("%s", op);
        if (op[0] == 'I') {
            scanf("%d", &x);
            before.push(x);
            sum += x;
            pn=before.size();
            f[pn] = max(f[pn - 1], sum);
//            printf("%d %d %d\n",pn,sum[pn],f[pn]);
        } else if (op[0] == 'D') {
            if (before.size() < 1) continue;
            x = before.top();
            before.pop();
            sum -= x;
        } else if (op[0] == 'L') {
            if (before.size() < 1) continue;
            x = before.top();
            before.pop();
            after.push(x);
            sum -= x;
        } else if (op[0] == 'R') {
            if (after.size() < 1) continue;
            x = after.top();
            after.pop();
            before.push(x);
            sum += x;
            pn=before.size();
            f[pn] = max(f[pn - 1], sum);
        } else {
            scanf("%d", &x);
            printf("%d\n", f[x]);
        }
    }
    return 0;
}
View Code

 

posted @ 2018-08-27 00:42  Acerkoo  阅读(346)  评论(0编辑  收藏  举报