Minimal string CodeForces

来源:互联网 发布:mac分屏 编辑:程序博客网 时间:2024/06/11 02:51

Petya recieved a gift of a string s with length up to 10^5 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:
1.Extract the first character of s and append t with this character.
2.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| ≤ 10^5), consisting of lowercase English letters.

Output
Print resulting string u.

Example
Input
cab
Output
abc
Input
acdb
Output
abdc

大致题意:给你一个字符串s(由小写字母组成)和两个空串t,u,现在有两个操作,1.将字符串s的第一个字符移动添加到t串的末尾。2.将t串末尾的字符移动添加到u串的末尾。让你输出u串填满后的最小字典序。

思路:简单的模拟,贪心的去找当前s串和t串末尾中最小的那个字符,然后将其移动添加到u串里输出。

代码如下

#include <cstdio>  #include <cstring>  #include <iostream> #include <algorithm>   #define ll long longusing namespace std; char s[100005];//s串char s2[100005];//t串int num[26];int main(){    std::ios::sync_with_stdio(false);    memset(num,0,sizeof(num));    cin>>s;    int l=strlen(s);    for(int i=0;i<l;i++)//记录每种字母出现的次数    num[s[i]-'a']++;    int len=0;//s2串长度    int x;    char c;    for(int i=0;i<26;i++)//找出当前s串中最小的字符    {        if(num[i]!=0)        {            c=i+'a';            break;        }    }    int i=0;    for(i=0;i<l;i++)//s串中找到第一个最小字符c输出,前面的保存到s2串中    {        if(s[i]!=c)        {            s2[len]=s[i];            len++;            num[s[i]-'a']--;        }        else        {            cout<<c;            num[c-'a']--;            break;        }    }    i++;    while(i<l)    {        int flag=0;        if(len==0)//如果s2串长度为0即s2串中此时没有字符        {            for(int i=0;i<26;i++)//找到此时的s串中最小字符            {                if(num[i]!=0)                {                c=i+'a';                break;                }            }            flag=1;        }        else         {            for(int j=0;j<s2[len-1]-'a';j++)//否则判断此时s串中是否有最小字符小于s2串的末尾字符            if(num[j]!=0)            {            c='a'+j;            flag=1;            break;            }        }        if(flag==1)//选择此时s串中的最小字符输出,在这前面的接着存到s2串里        {            while(1)            {                if(s[i]!=c)                {                    s2[len]=s[i];                    len++;                    num[s[i]-'a']--;                    i++;                }                else                {                    cout<<c;                    num[c-'a']--;                    i++;                    break;                }            }        }        else //选择s2串的最后一个字符        {            cout<<s2[len-1];            len--;        }    }    for(int j=len-1;j>=0;j--)//最后倒着输出s2串中的字符    cout<<s2[j];    return 0;} 
原创粉丝点击