Codeforces 797C Minimal string【贪心】

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

题目大意:

给你一个栈,然你找到一个出栈顺序,使得字典序最小。


思路:


逆序维护一个数组minn【i】=x,表示第i个位子后边最小的字符是x.

那么对应维护一个栈,如果此时栈顶字符小于等于minn【此时要加入的元素的位子】,那么就出栈,将栈顶这个字符输出;

同时每个字符都在操作结束后入栈。


Ac代码:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<stack>
using namespace std;
char ss[100800];
int a[100800];
int minn[100800];
int main()
{
    while(~scanf("%s",ss))
    {
        int n=strlen(ss);
        memset(minn,0,sizeof(minn));
        for(int i=0;i<n;i++)a[i]=ss[i]-'a'+1;
        for(int i=n-1;i>=0;i--)
        {
            if(i==n-1)minn[i]=a[i];
            else minn[i]=min(minn[i+1],a[i]);
        }
        stack<char >s;
        for(int i=0;i<n;i++)
        {
            if(s.size()==0)
            {
                s.push(ss[i]);
            }
            else
            {
                while(!s.empty())
                {
                    int u=s.top()-'a'+1;
                    if(u<=minn[i])
                    {
                        printf("%c",s.top());
                        s.pop();
                    }
                    else break;
                }
                s.push(ss[i]);
            }
        }
        while(!s.empty())
        {
            printf("%c",s.top());
            s.pop();
        }
        printf("\n");
    }
}









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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值