您的位置:首页 > 其它

zoj 3829 Known Notation(贪心)

2014-10-13 09:36 351 查看
题目链接:zoj 3829 Known Notation

题目大意:给定一个不完整的后缀表达式,要求有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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: