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 的每一个字母,只需要确定后面是否还有比当前字母小的字母,如果有,这个字母就存下来,前往下一个字母,如果没有,这个字母就直接添加到 u,最后统一将存下来的字母逆序添加到 u 就可以了。 至于判断一个字母后面是否还有比当前字母小的, 就需要先统计每个字母的个数,接着暴力从 a 到 这个字母的前一个字母 判断这些字母的个数是不是为 0 就可以了。 然后 如果这个字母添加到 u 了,它的个数就 - - ,
AC代码:
#include<bits/stdc++.h>
using namespace std;
int coun[26] = {0};
bool _find(char x){
int n = x - 'a';
for(int i = 0;i < n;i ++)
if(coun[i]) return 1;
return 0;
}
int main() {
char s[100050];
while(~scanf("%s",s)){
char ans[100050] = {0};
int pa = 0;
memset(coun,0,sizeof(coun));
int len = strlen(s);
for(int i = 0;i < len;i ++)
coun[s[i] - 'a'] ++;
stack<char> st;
// st.push(s[0]); coun[s[0] - 'a'] --;
for(int i = 0;i < len;i ++){
while(!st.empty() && !_find(st.top())){
ans[pa ++] = st.top();
st.pop();
}
st.push(s[i]);
coun[s[i] - 'a'] --;
}
while(!st.empty()){
ans[pa ++] = st.top();
st.pop();
}
puts(ans);
}
return 0;
}