CodeForces 797C Minimal string

题目大意:给定一段字符串,用栈做容器,确定字符的入栈和出栈顺序,将字符串变为字典序最小并输出

算法:
(1) 遍历字符串,直到栈为空,将栈中小于当前字符的字符全部出栈。再将当前字符压栈。
(2) 若遍历完,栈不为空,将栈中字符全部出栈
启示:能压栈的尽量压,每次枚举满足条件的能出栈尽量出栈

#include <cstdio>
#include <stack>
#include <cstring>

using namespace std;
char str[100010];
char minch[100010];

int main()
{
    scanf("%s", str);
    int len = strlen(str);
    minch[len-1] = str[len-1];
    for(int i = len-2; i >= 0; --i)
        minch[i] = str[i]<minch[i+1]?str[i]:minch[i+1];
    stack <char> s;
    for(int i = 0; i < len; ++i)//bac
    {
        while(!s.empty())
        {
            if(s.top()>minch[i]) break;
            printf("%c", s.top());
            s.pop();
        }
        s.push(str[i]);//能压尽量压,每次枚举能出尽量出
    }
    while(!s.empty())
    {
        printf("%c", s.top());
        s.pop();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jay__bryant/article/details/81228335