• 【codeforces 797C】Minimal string


    【题目链接】:http://codeforces.com/contest/797/problem/C

    【题意】

    一开始,给你一个字符串s;两个空字符串t和u;
    你有两种合法操作;
    1.将s的开头字符加到t后面;
    2.将t的最后一个字符加到u的后面去
    要求最后使得s和t字符串变成空串;
    并且得到的u的字符串的字典序最小;

    【题解】

    i层循环顺序枚举s字符串的每一个字符;
    然后把这第i个字符s[i]加入到t的后面去->用一个栈来模拟;
    然后维护栈顶的元素和s中剩下的字符串里面字典序最小的字母;->O(26)得到;设为now;
    如果栈顶元素为now;
    就把栈顶元素弹到答案字符串后面去;
    然后把新的栈顶元素再考虑进去,然后再求字典序最小的字母;
    重复上述步骤直至字典序最小的字母不为栈顶元素为止;
    这样做就是贪心地保证从最高位开始每一位的字典序都是最小的;

    【Number Of WA

    3

    【完整代码】

    #include <bits/stdc++.h>
    using namespace std;
    #define lson l,m,rt<<1
    #define rson m+1,r,rt<<1|1
    #define LL long long
    #define rep1(i,a,b) for (int i = a;i <= b;i++)
    #define rep2(i,a,b) for (int i = a;i >= b;i--)
    #define mp make_pair
    #define pb push_back
    #define fi first
    #define se second
    #define ms(x,y) memset(x,y,sizeof x)
    
    typedef pair<int,int> pii;
    typedef pair<LL,LL> pll;
    
    const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
    const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
    const double pi = acos(-1.0);
    const int N = 1e5+100;
    
    int bo[300],len;
    char s[N],now;
    stack <char> sta;
    string ans;
    
    char get_now()
    {
        for (char t = 'a';t <='z';t++)
            if (bo[t])
                return t;
        return '%';
    }
    
    int main()
    {
        //freopen("F:\rush.txt","r",stdin);
        ios::sync_with_stdio(false);
        ans="";
        cin >> (s+1);
        len = strlen(s+1);
        rep1(i,1,len)
            bo[s[i]]++;
        rep1(i,1,len)
        {
            now = get_now();
            sta.push(s[i]);
            while (!sta.empty() && sta.top()==now)
            {
                //assert(sta.top()==now);
                ans+=now;
                bo[now]--;
                sta.pop();
                if (!sta.empty())
                    bo[sta.top()]++;
                now = get_now();
            }
            if (!sta.empty())
                bo[sta.top()]--;
        }
        while (!sta.empty()) ans+=sta.top(),sta.pop();
        cout << ans << endl;
        //printf("
    %.2lf sec 
    ", (double)clock() / CLOCKS_PER_SEC);
        return 0;
    }
    
  • 相关阅读:
    ZOJ 3018
    poj2464
    Gauss
    【C】关于内存地址
    【C】typedef与define的区别
    C位移操作
    操作系统使用批处理文件更改网络配置
    【Linux】查看某个进程的线程数量(转)
    数据结构快速排序
    C++Explanation of ++val++ and ++*p++ in C
  • 原文地址:https://www.cnblogs.com/AWCXV/p/7626408.html
Copyright © 2020-2023  润新知