---
title: "zoj 3829 Known Notation(贪心)"
author: "阿尔萨斯"
date: "2014-10-13T09:36:00Z"
tags: []
slug: "zoj-3829-known-notation"
draft: false
lastmod: "2014-10-13T12:41:34Z"
id: 2130363
url: "https://xwk.iteye.com/blog/2130363"
---

[题目链接：zoj 3829 Known Notation](http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3829)

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

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