ZOJ 3829 Known Notation 贪心
来源:互联网 发布:淘宝阿尔法软件 编辑:程序博客网 时间:2024/05/18 03:15
题意:给出一个后缀表达式,表达式中不含有空格,用如下的操作使整个表达式合法。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;}
0 0
- zoj 3829 Known Notation(贪心)
- zoj 3829 Known Notation 贪心
- ZOJ 3829 Known Notation 贪心
- zoj 3829 Known Notation (贪心)
- [贪心+模拟] zoj 3829 Known Notation
- ZOJ 3829 Known Notation --贪心+找规律
- ZOJ 3829 Known Notation(贪心)
- ZOJ 3829 Known Notation【贪心】【好题】
- ZOJ - 3829 Known Notation
- ZOJ 3829 Known Notation
- zoj 3829 Known Notation
- zoj 3829 Known Notation
- ZOJ - 3829 Known Notation
- ZOJ 3829 Known Notation
- ZOJ-3829-Known Notation
- ZOJ 3829 Known Notation
- Zoj 3829 Known Notation
- ZOJ Problem Set - 3829Known Notation(贪心)
- C语言中fpritnf函数的简单理解
- INSTALL_FAILED_NO_MATCHING_ABIS 的解决办法
- 在Eclipse中配置tomcat,浏览器输入http://localhost:8080报404错误解决方法
- 快速构建网站之获取域名
- 数据库的查询
- ZOJ 3829 Known Notation 贪心
- 第二次实验 实验报告
- 《VC++深入详解》第二章练习
- [ACM] FZU 2086 餐厅点餐 (枚举)
- Java单例模式常用的3种实现方式
- mkdir: cannot create directory `/usr/local/share/man/man1': File exists
- Mysql数据隔离,脏读,rollback
- Oracle 字符串函数和数字函数,聚集函数
- 由json字串生成json对象时的转义问题