Editor (HDU - 4699,对顶栈模拟数据结构)

一.题目链接:

HDU-4699

二.题目大意:

模拟实现以下操作:

I x:在光标后插入数 x,并将光标移到 x 后面.

D:删除光标的前一个数.

L:将光标左移.

R:将光标右移.

Q x:求 1 ~ x 中前缀和的最大值.

三.分析:

与对顶堆类似,这里用对顶栈实现.

即准备两个栈,光标前面的为 s1,光标后面的为 s2.

同时开两个数组,一个存前缀和,一个存前缀和的最大值.

详见代码.

四.代码实现:

#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-8
#define lc k * 2
#define rc k * 2 + 1
#define pi acos(-1.0)
#define ll long long int
using namespace std;

const int M = (int)1e6;
const ll mod = (ll)1e9 + 7;
const int inf = 0x3f3f3f3f;

int sum[M + 5];
int sum_Max[M + 5];
stack <int> s1, s2;

void init()
{
    while(!s1.empty())  s1.pop();
    while(!s2.empty())  s2.pop();
    sum[0] = 0;
    sum_Max[0] = -inf;
}

int main()
{
    char ch;
    int q, x, pos;
    while(~scanf("%d", &q))
    {
        init();
        pos = 0;
        while((q--) > 0)
        {
            getchar();
            ch = getchar();
            if(ch == 'I')
            {
                scanf("%d", &x);
                s1.push(x);
                pos++;
                sum[pos] = sum[pos - 1] + x;
                sum_Max[pos] = max(sum_Max[pos - 1], sum[pos]);
            }
            else if(ch == 'D' && !s1.empty())
            {
                s1.pop();
                pos--;
            }
            else if(ch == 'L' && !s1.empty())
            {
                s2.push(s1.top());
                s1.pop();
                pos--;
            }
            else if(ch == 'R' && !s2.empty())
            {
                s1.push(s2.top());
                s2.pop();
                pos++;
                sum[pos] = sum[pos - 1] + s1.top();
                sum_Max[pos] = max(sum_Max[pos - 1], sum[pos]);
            }
            else if(ch == 'Q')
            {
                scanf("%d", &x);
                printf("%d\n", sum_Max[x]);
            }
        }
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值