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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章