题解:P8082 [COCI 2011/2012 #4] KEKS

· · 题解

题目传送门

提前说明:完整代码有些压行,码风较丑,不喜勿喷,谢谢orz。

solution

分析题目:

给定正整数 N,K 和一个 N 位数,求在 N 位数中删除 K 位后剩下的数的最大值。关注最大值三个字,所以可以考虑用单调栈。

现在开始分析代码
先输入 N,K,S (S 代表 N 位数),用单调栈维护剩下 N - K 位数的最大值:

for(int i = 1;i <= n;i++)
{
    while(!sta.empty() && sum < k && sta.top() < s[i] - '0') {sum++;sta.pop();}  //维护单调栈,删不超过K位
    sta.push(s[i] - '0');
}

因为栈只支持后进先出,所以我们倒置整个栈,再输出:

for(int i = 1;i <= n - k;i++)
{
  sta1.push(sta.top());
  sta.pop();
}
for(int i = 1;i <= n - k;i++)
{
    cout << sta1.top();
    sta1.pop();
}

最后一个环节(你们最喜欢的代码来了。)

::::success[AC代码]

#include<bits/stdc++.h>
using namespace std;
string s;
int n,k,sum;
stack<int> sta,sta1;  //栈,倒置后的栈
int main()
{
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);  //加速代码
    cin >> n >> k >> s;
    s = " " + s;
    for(int i = 1;i <= n;i++)
    {
        while(!sta.empty() && sum < k && sta.top() < s[i] - '0') {sum++;sta.pop();}
        sta.push(s[i] - '0');
    }  //单调栈核心代码
    for(int i = 1;i <= n - k;i++) {sta1.push(sta.top());sta.pop();}  //倒置
    for(int i = 1;i <= n - k;i++) {cout << sta1.top();sta1.pop();}  //输出
    return 0;
}

//代码较丑,不喜勿喷

::::

AC记录

完结撒花qwq