【HDOJ4699】Editor(对顶栈,模拟)

problem

  • 维护一个整数序列的编辑器,支持5种操作,操作数< 1e6
  • I x:在光标后插入数x,插入后光标移到x后
  • D:删除光标前的一个整数
  • L:光标左移一个位置
  • R:光标右移一个位置
  • Q k:询问k之前的最大前缀和,k不超过光标位置

solution

  • 特殊性:I,D,L,R都在光标位置修改。所以想到对顶栈。
  • 再开一个数组f维护栈A的前缀和的最大值即可。

codes

#include<cstdio>
#include<algorithm>
#include<stack>
using namespace std;
const int maxn = 1e6+10;
int f[maxn];
int main(){
    int T;
    while(scanf("%d",&T)!=EOF){
        stack<int>A,B;
        int sum = 0;//到光标为止的前缀和
        f[0]=-999999999;
        while(T--){
            char op[20];
            scanf("%s",op);
            if(op[0]=='I'){
                int x; scanf("%d",&x);
                A.push(x);
                sum += x;
                int cur = A.size();
                f[cur] = max(sum, f[cur-1]);
            }else if(op[0]=='D'){
                if(A.size()>=1){
                    sum -= A.top();
                    A.pop();
                }
            }else if(op[0]=='L'){
                if(A.size()>=1){
                    sum -= A.top();
                    B.push(A.top());
                    A.pop();
                }
            }else if(op[0]=='R'){
                if(B.size()>=1){
                    A.push(B.top());
                    sum += B.top();
                    int cur = A.size();
                    f[cur] = max(sum,f[cur-1]);
                    B.pop();
                }
            }else if(op[0]=='Q'){
                int k; scanf("%d",&k);
                printf("%d
",f[k]);
            }
        }
    }
   return 0;
}
原文地址:https://www.cnblogs.com/gwj1314/p/9444600.html