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

来源:互联网 发布:久久网络 编辑:程序博客网 时间:2024/06/06 03:53
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 100005using 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;}


0 0
原创粉丝点击