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

题目: 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; 
}


发布了125 篇原创文章 · 获赞 4 · 访问量 10万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章