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.
Examples
Input
cab
Output
abc
Input
acdb
Output
abdc
题解:维护一个minn[] 数组表示第 i 个位置后面 最小的 字符,就行了;
#include <iostream>
#include <stack>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn=1e5+7;
char s[maxn];
int a[maxn];
int minn[maxn];//minn[i],储存第i个位子后边最小的字符
//如果此时栈顶字符小于等于minn[i],那么就出栈,将栈顶这个字符输出;
int main()
{
while(cin>>s)
{
int len=strlen(s);
for(int i=0; i<len; i++)
a[i]=s[i]-'a';
for(int i=len-1; i>=0; i--)
{
if(i==len-1) minn[i]=a[i];
else minn[i]=min(minn[i+1], a[i]);
}
stack<int> st;
for(int i=0; i<len; i++)
{
if(st.size()==0)
st.push(a[i]);
else
{
while(!st.empty())
{
int u=st.top();
if(u<=minn[i])
{
printf("%c",st.top()+'a');
st.pop();
}
else break;
}
st.push(a[i]);
}
}
while(!st.empty())
{
printf("%c",st.top()+'a');
st.pop();
}
printf("\n");
}
return 0;
}