【CodeForces 797C】Minimal string(貪心+字符串)

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

題目大意:給一個字符串s,兩個空字符串t,u,有兩種操作,1.將s的第一個字母加到t後,2.將t的最後一個字母加到u後,最後得到字典序最小的字符串u

思路:統計s中每個字母出現的次數,用棧模擬t,第一個字母一定是s中最小的字母,之後有兩種選擇,如果當前沒入棧的字母中有比棧頂字母小的,則繼續入棧,若果沒有,則出棧並將棧頂字母給u,每次判斷棧頂元素後有無比它小的字母

#include <bits/stdc++.h>
#define manx 100005
using namespace std;
int a[27];
bool found(char c) //當前字符的後面是否有比它小的字符,有則s to t,否則 t to u
{
    int n=c-'a';
    for (int i=0; i<n; i++){
        if (a[i]) return true;
    }
    return false;
}
int main()
{
    char s[manx],u[manx];
    while(~scanf("%s",s)){
        stack<char>q;
        memset(a,0,sizeof(a));
        memset(u,0,sizeof(u));
        int l=strlen(s);
        for (int i=0; i<l; i++)    //統計每個字母出現的次數
            a[s[i]-'a']++;
        int j=0;
        q.push(s[0]);
        a[s[0]-'a']--;
        int cot=0;
        for (int i=1; i<l; i++){
            while (!q.empty()&& !found(q.top()) ){
                char t=q.top();
                u[cot++]=t;
                q.pop();
            }
            q.push(s[i]);
            a[s[i]-'a']--;   //a表示沒入棧的每個字母的個數
        }
        while(!q.empty()){
            u[cot++]=q.top();
            q.pop();
        }
        puts(u);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章