Codeforces 797C Minimal string 简单模拟

来源:互联网 发布:网络视频广告限制 编辑:程序博客网 时间:2024/06/08 05:44

[SUMMER TRAIN] D1 C
题目链接 http://codeforces.com/contest/797/problem/C

题意: 给一个字符串 s, 给定三个操作
- 1. 将 s 串的第一个字母移动到一个栈中
- 2. 将 s 串的第一个字母移动到字符串 u 的尾部
- 3. 将栈顶的字母移动到字符串 u 的尾部
求字典序最小的 u 串. (s 串空, 栈空)

简单模拟就好.
易知, 目标串中 assic 值越小的字母应该越靠前. 所以按照字典序最小的方式模拟
即: 先将所有的 ‘a’ 移动到 u 串中, 再将剩余 s 串中的所有 ‘b’ 移动到 u 串中…….

坑点: 需要比对栈顶与 s 串头的大小.
比如:

                u串: aaaabbbcccdddd                 栈: cciugic                s 串剩余: ejjiopjio

此时应将栈中的字母 ‘c’ 压至目标串尾.

代码如下:

#include <stdio.h>#include <iostream>#include <stack>#include <queue>using namespace std;queue <char> s;stack <char> t;queue <char> u;int cnt[30];void init() {    while (s.size()) s.pop();    while (t.size()) t.pop();    while (u.size()) u.pop();    for (int i = 0; i < 30; ++i)         cnt[i] = 0;}bool getin() {    init();    char c = 0;    while (scanf("%c", &c) == 1 && c != '\n' && c != EOF)        s.push(c), cnt[c-'a']++;    return (!s.empty());}void putout() {    while (u.size())         putchar(u.front()), u.pop();    putchar('\n');}void compute() {    int itor = 0;    while (cnt[itor] == 0) ++itor;    while (!s.empty()) {        while (!t.empty() && t.top() <= 'a'+itor) {            u.push(t.top()), t.pop();        }        while (cnt[itor]) {            cnt[s.front()-'a']--;            if (s.front() == 'a' + itor)                 u.push(s.front());            else                t.push(s.front());            s.pop();        }        itor++;    }    while (!t.empty())        u.push(t.top()), t.pop();}int main() {        while (getin()) {        compute();        putout();    }    return 0;}

2017-08-17

原创粉丝点击