题意:给出一个后缀表达式,表达式中不含有空格,用如下的操作使整个表达式合法。1.添加操作:可以向表达式中增加一个数字或一个乘号。2.交换操作:交换表达式中的一个数字和一个乘号。现在希望用最少的操作使整个表达式合法。
思路:贪心。仔细想,我们可以得到下面的性质:
1.数字在表达式的前面,灵活性更高.乘号在表达式的后面,灵活性更高。
2.交换操作可以等价于一个两个添加操作(一个添加数字,一个添加乘号)。
3.数字的个数应该大于等于乘号个数+1.
4.添加乘号的操作是没有必要的。因为添加一个乘号,还要添加两个数字才能合法。
所以我们的可以这样操作:1.如果数字的个数不足,我们直接将数字添加到合法的最少的数量。2.之后,我们只需交换操作就行了。
但是,怎么交换呢? 根据前面的性质我们可以知道,乘号要往后放,数字要往前放,所以,我们直接搜索找到最后的可以放的位置即可。(现场赛就被坑在这里了。。。。)
注意:对于这道题,还要讨论很多情况:1.如果整个表达式全是数字,也是合法的。2.如果前面的表达式是合法的,但是表达式最后出现了数字,我们需要一次交换操作。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cctype>
using namespace std;
int main(void)
{
//freopen("input.txt","r",stdin);
char str[5000];
int T;
scanf("%d", &T);
while(T--){
scanf("%s",str);
int len = strlen(str);
int cnt1 = 0, cnt2 = 0;
int cnt = 0;
int ans = 0;
int last = len-1;
for(int i = 0; i < len; ++i)
if(isdigit(str[i]))
cnt1++;
else
cnt2++;
if(cnt1 < cnt2 + 1)
ans = cnt = cnt2 + 1 - cnt1;
if(cnt1 == len){
puts("0");
continue;
}
for(int i = 0; i < len; ++i){
if(isdigit(str[i]))
cnt++;
else if(cnt >= 2)
cnt--;
else{
while(str[last] == '*') last--;
if(last > i){
swap(str[last],str[i]);
cnt++;
ans++;
}
}
}
if(str[len-1] != '*')
ans++;
printf("%d\n",ans);
//printf("%s\n",str);
}
return 0;
}