C. Minimal string

来源:互联网 发布:c语言倒九九乘法表 编辑:程序博客网 时间:2024/06/08 15:13

C. Minimal string
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

题解:扫一遍,然后记录每个字母出现的次数。每次对某一个字母进行操作后,该字母次数减一。

可以想到,要找最小的字典序序列,只需要每次找最小的字母并且压入结果字符串即可。字母权值为第一优先度

代码如下:

#include <iostream>#include <stack>using namespace std;string s,ans;stack<char> t;int arr[30]={0};int find( ){    int i=0;    while(arr[i]==0)        i++;    return i;}void solve( ){    int i=0;    while(i<s.size())    {       if(t.size()==0)       {           t.push(s[i]);           arr[s[i]-'a']--;           i++;       }        else        {            int temp=t.top()-'a';            int tt=0;            for(int j=0;j<temp;j++)            {                if(arr[j]>0)                    tt=1;            }            if(tt)            {                t.push(s[i]);                arr[s[i]-'a']--;                i++;            }            else            {                ans+=t.top();                t.pop();            }        }            }    while(t.size())    {        ans+=t.top();        t.pop();    }    cout<<ans<<endl;}int main( ){    for(int i=0;i<30;i++)        arr[i]=0;    cin>>s;    for(int i=0;i<s.size();i++)    {        arr[s[i]-'a']++;    }    solve( );    return 0;}





0 0
原创粉丝点击