UVa:11491 Erasing and Winning(单调栈)

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=845&page=show_problem&problem=2486

题意:你是一个电视节目的获奖嘉宾。主持人在黑板上写出一个n位整数(不以0开头),邀请你删除其中的d个数字,剩下的整数便是你所获得的奖品的价值。当然,你希望这个奖品价值尽量大。 1d<n105 (本段摘自《算法竞赛入门经典(第2版)》)

分析:
开始是认为是贪心,去寻找不下降序列,将序列的最后一个元素保留,但是这个想法是错的,过不了如下数据:6 3 121314,如果采用贪心得到的结果是234,但是正确答案是314。正确想法是单调栈,维护一个单调递减栈即可。

代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>

using namespace std;

const int maxn = 100000 + 5;

int cnt, n, d;
char s[maxn], ans[maxn];
stack< char > sta;

int main()
{
    while (~scanf("%d%d", &n, &d), n || d)
    {
        cnt = 0;
        scanf("%s", s);
        for (int i = 0; i < n; ++i)
            if (sta.empty())
                sta.push(s[i]);
            else
            {
                if (s[i] <= sta.top())
                    sta.push(s[i]);
                else
                {
                    while (!sta.empty() && d && sta.top() < s[i])
                    {
                        sta.pop();
                        --d;
                    }
                    sta.push(s[i]);
                }
            }
        while (!sta.empty())
        {
            ans[cnt++] = sta.top();
            sta.pop();
        }
        for (int i = cnt - 1; i >= d; --i)
            printf("%c", ans[i]);
        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值