您的位置:首页 > 其它

ZOJ 3829 Known Notation / 2014牡丹江区域赛 K (模拟, 贪心)

2014-10-14 20:41 489 查看
题目: LINK

给定一个字符串只含'1' ~ '9' 和'*',两个操作:插入和任意交换字符串两个字符,求最少的操作数使得字符串变成后缀表达式,

如果数字个数x - '*'个数y < 1,那么必须添加数字, 而且最优的情况肯定在字符串的前面加y-x+1个数字。

之后模拟, 从得到的新字符串的头开始处理, 遇到数字cou++, 遇到'*',如果cou>=2, cou--,否则要进行交换操作,贪心一下, 肯定是把这个'*'和从后面开始能找到的第一个数字交换,这样处理到最后。

注意全是数字的数字。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <queue>
#include <map>
#include <set>
using namespace std;
#define INF 1000000000
//typedef __int64 LL;
#define N 1111
int n;
string str;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int t;
scanf("%d", &t);
while(t--) {
cin>>str;
int la , lb;
la = lb = 0;
for(int i = 0; i < str.length(); i ++) {
if(str[i] == '*') lb ++;
else la ++;
}
if(la == str.length()) {
puts("0"); continue; //notice this ..
}
int ans = 0;
if(lb >= la) {
ans += lb - la + 1;
for(int i = 0; i < lb - la + 1; i++) str = "1"+str;
}
int aa = 0;
int flag = 0;
for(int i = 0; i < str.length(); i++) {
if(str[i] != '*') {
aa ++;
}
else {
flag = 1;
if(aa >= 2) {
aa--;
}
else {
for(int j = str.length()-1; j>= 0; j--) {
if(str[j] != '*') {
str[j] = '*'; str[i] = '1';
break;
}
}
aa ++;
ans ++;
}
}
}
int len = str.length();
if(str[len-1] != '*') ans ++;
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: