Codeforces 797C-Minimal string

来源:互联网 发布:centos配置内网ip 编辑:程序博客网 时间:2024/06/05 15:25

题目

Codeforces 797C
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Petya recieved a gift of a string s with length up to 105 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves:

Extract the first character of s and append t with this character.
Extract the last character of t and append u with this character.

Petya wants to get strings s and t empty and string u lexigraphically minimal.

You should write a program that will help Petya win the game.

Input

First line contains non-empty string s (1 ≤ |s| ≤ 105), consisting of lowercase English letters.

Output

Print resulting string u.

Examples

Input

cab

Output

abc

Input

acdb

Output

abdc

题目大意

一开始,给你一个字符串s;两个空字符串t和u;你有两种合法操作;
1.将s的开头字符加到t后面;
2.将t的最后一个字符加到u的后面去;要求最后使得s和t字符串变成空串;并且得到的u的字符串的字典序最小;


换一种方式理解,给一个字符串s,对字符串从首位开始进行压栈和出栈操作,使得字典序最小

解题思路

要想使得字典序最小,就要使比较小的字母尽可能多的输出,比如abcdgaaa,结果一定是aaagdcb。
首先用数组sum记录s中每个英文字幕出现的次数
接下来遍历字符串s,记未访问的字符串中最小的字母是第f个英文字母(f从0开始)。
当栈S非空时,将栈顶满足S.top() <= f的字符输出。当s[i]是当前未访问的s中的字符最小值的时候,将s[i]输出,否则将s[i]放到栈S中。

最后把栈S中剩余的字母按顺序输出


AC代码

#include <cstdio>#include <iostream>#include <stack>#include <cstring>using namespace std;#define CL(a) memset(a,0,sizeof a)const int maxn = 1e5+10;char a[maxn];//字符串sint sum[25];stack<char>S;int main(){    int f;    while (scanf("%s",a) != EOF){        for (;!S.empty();S.pop());        CL(sum);        f = 0;        for (int i = 0;a[i] != 0;i++)            sum[a[i]-'a']++;        for (int i = 0;a[i] != 0;i++){            while (!sum[f] && f < 25)//寻找未访问的部分最最小的字母是第几个字母(从0开始)                f++;            while (!S.empty() && S.top() <='a' + f){//若栈顶元素比'a'+f小则输出                printf("%c",S.top());                S.pop();            }            if (a[i]- 'a' == f){                printf("%c",a[i]);                sum[f]--;            }            else{                sum[a[i]-'a']--;                S.push(a[i]);            }        }        while (!S.empty()){            printf("%c",S.top());            S.pop();        }        printf("\n");    }    return 0;}