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

6 篇文章 0 订阅
4 篇文章 0 订阅
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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值