首页 > 代码库 > Codeforces 797C. Minimal string

Codeforces 797C. Minimal string

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 lexicographically 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.

开一个26字母的数组来方便的管理当前s里最小的字符

然后每次将s的第一个字符入栈,如果栈顶比s剩下的字符都小就出栈直到不满足这个情况或栈空。

s入完后,把所有栈内的元素依次出栈

技术分享
#include <cstdio>
#include <cmath>
#include <cctype>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
typedef long long LL;

string s;
int ch[29] = {0};
stack<char> st;
int main() {
  // freopen("test.in","r",stdin);
  ios::sync_with_stdio(false);
  cin >> s;
  int len = s.length();
  for (int i=0;i<len;i++){
    ch[s[i] - a] ++;
  }
  int now = 0;
  while (ch[now] == 0 && now <= 25){
    now ++;
  }
  for (int i=0;i<len;i++){
    ch[s[i] - a] --;
    if (s[i] != now + a){
      st.push(s[i]);
    }
    else {
      cout << s[i];
    }
    while (ch[now] == 0 && now <= 25){
      now ++;
    }
    while (!st.empty() && st.top() <= now + a){
      cout << st.top();
      st.pop();
    }
  }
  while (!st.empty()){
    cout << st.top(); st.pop();
  }
  return 0;
}
View Code

 

Codeforces 797C. Minimal string