CodeForce-797C Minimal string(贪心模拟)

Minimal string

CodeForces - 797C

Petya 收到一个长度不超过 105 的字符串 s。他拿了两个额外的空字符串 tu 并决定玩一个游戏。这个游戏有两种合法操作:

  • s 串的第一个字符移动到字符串 t 的末尾。
  • t 串的最后一个字符移动到字符串 u 的末尾。

Petya 希望将 st 都变为空串并且使得串 u 字典序最小。

你需要写一个代码求出最小的字典序。

Input

第一行包含一个非空串 s (1 ≤ |s| ≤ 105),只包含小写字母。

Output

输出串 u.

保存每个字符的出现次数 当前位置可以填入的字符要么为当前栈顶 若有比栈顶还小的字符 则找到该字符即可

#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 20;
string s, t, u, a;

int b[30];   
int pos[30]; 
int h[N];
stack<char> sta;
int main()
{
    while (cin >> s)
    {
        int len = s.length();
        memset(b, 0, sizeof(b));

        for (int i = 0; s[i]; i++)
            b[s[i] - 'a']++;
        int i = 0, k;
        while (s[i])
        {
            int k1 = 26;
            if (!sta.empty())
                k1 = sta.top() - 'a';
            for (k = 0; k < 26; k++)
            {
                if (b[k])
                    break;
            }
            k = min(k1, k); 
            while (true)
            {
                if (!sta.empty() && sta.top() - 'a' == k) 
                    break;
                b[s[i] - 'a']--;
                sta.push(s[i++]);
                if (s[i] == '')
                    break;
            }
            if (!sta.empty())
            {
                printf("%c", sta.top());
                sta.pop();
            }
        }
        while (!sta.empty())
        {
            char c = sta.top();
            sta.pop();
            printf("%c", c);
        }
        cout << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/YingZhixin/p/7116947.html