`
阿尔萨斯
  • 浏览: 4169044 次
社区版块
存档分类
最新评论

zoj 3829 Known Notation(贪心)

 
阅读更多

题目链接:zoj 3829 Known Notation

题目大意:给定一个不完整的后缀表达式,要求有2种不同操作,用尽量少的操作使得表达式完整。

解题思路:贪心,数字的个数要要保证比的个数多1,不够的话优先补在开头是最优的。然后遍历一遍字符串,碰到数字+1,碰到-1,保证数字的个数大于等1,如果不够减的话,可以和最后面的一个数字交换位置(用栈维护十分方便),因为添加和交换代价都是1。
不过这题数据实在够弱的,因为111这种情况,至少需要添加一个号才可以(特判即可),但是居然也可以过,同步赛的时候因为考虑了这个还WA了一次,因为11的情况还是为0的。

#include <cstdio>
#include <cstring>
#include <stack>
#include <algorithm>

using namespace std;

const int maxn = 1005;
char s[maxn];

int solve () {
    stack<int> sta;

    int len = strlen(s), c = 0;
    for (int i = 0; i < len; i++) {
        if (s[i] == '*')
            c++;
        else
            sta.push(i);
    }

    if (c == 0)
        return 0;

    int n = len - c;
    int ret = n = max(c + 1 - n, 0);

    for (int i = 0; i < len; i++) {
        if (s[i] == '*') {
            if (n <= 1) {
                s[sta.top()] = '*';
                sta.pop();
                n++;
                ret++;
            } else
                n--;
        } else 
            n++;
    }

    if (ret == 0 && s[len-1] != '*')
        ret++;
    return ret;
}

int main () {
    int cas;
    scanf("%d", &cas);
    while (cas--) {
        scanf("%s", s);
        printf("%d\n", solve());
    }
    return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics