【CCF】201903-2-二十四點

pictuer

這裏有幾個注意得點(1)關於輸入得稱號一定是x,而不是*號。有個20分得點。
(2)關於存儲數字要定義成int類型,因爲6x4+4/5=24; 這個我之前定義成double所以結果造成除法出錯。
(3)運算符得優先級我這裏用map存儲,在進入棧得時候分運算符棧和數字棧。

最後 提交2

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<cctype> 
#include<map>
using namespace std; 
/*
	二十四點問題:
		中綴表達式計算問題 
*/
const int maxN = 10;
map<char, int> p; 
bool compareOp(char a, char b){
	return p[a] <= p[b];	
}
double cal(int a, int b, char op){
	int num;
	switch(op){
		case '+': num = a + b; break;
		case '-': num = a-b;break;
		case 'x': num = a*b;break;
		case '/': num = a / b; break;
	}
	return num;
}
void solve(int* number,char* op,int &topN, int &top){
	int num1 = number[topN];
	topN--;
	int num2 = number[topN];
	topN--;
	int num = cal(num2,num1, op[top]);
	topN++;
	*(number+topN) = num;
//	*(number+topN) = num;
	top--;
}
int main(){
	int n;
	scanf("%d",&n);
	string s;
	
	//定義優先級 
	p['+'] = p['-'] = 1;
	p['x'] = p['/'] = 2;
	
	while(n--){
		cin>>s; 
		int number[maxN];
		char op[maxN];
		int topN = -1,top=-1;

		for(int i = 0; i < s.size(); i++){
			if(isdigit(s[i])){
				number[++topN] = s[i]-'0';//因爲輸入都是單個數字 
			}else{
				//如果是操作符
				while(top != -1 && compareOp(s[i],op[top])) {
					//運算符棧不爲空,並且棧頂運算符的優先級>= s[i]
					solve(number,op,topN,top);
				}
				op[++top] = s[i];	//當前運算符進棧 
			}
		}
		//符號棧不爲空得情況 
		while(top != -1){
			solve(number,op,topN,top);
		}//推出時符號棧已經爲空 
		
		if(number[0] == 24){
			cout<<"Yes\n";
		}else{
			cout<<"No\n";
		}
	}
	return 0;
}
/*
5
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
*/
/*
2
6x7-3x6
6x4+4/5
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章