CCF 201903-2 二十四点

分析:

本题考察栈的基本应用-表达式求值,虽然不难,但是要想不用栈,直接模拟出先算乘除后算加减的过程也是不易的,过了样例提交不得分的情况也是很常见的,所以为了保险起见还是直接用栈模拟中缀表达式的计算过程。

首先,输入确保数字都是一位数,而且运算都只涉及加减乘除。我们维护一个操作数栈和一个操作符栈,遍历表达式,遍历到数时直接压入操作数栈即可;遍历到操作符时,当且仅当操作符栈非空且操作符栈顶元素的优先级大于等于遍历到的元素优先级时,才从操作数栈弹出两个操作数,同时弹出操作符栈的栈顶元素进行运算后将新的操作数压入操作数栈,最后将遍历到的操作符压入操作符栈。

注意:遍历完一遍表达式后,可能操作符栈还有操作符未进行运算,继续不断弹出操作符进行运算即可。

#include <iostream>
#include <cstdio>
#include <stack>
#include <cctype>
#include <cstring>
using namespace std;
int solve(int x,int y,char c){
	switch(c){
		case '+':
			return x + y;
		case '-':
			return x - y;
		case 'x':
			return x * y;
		case '/':
			return x / y;
	}
}
int main() {
	int T;
	cin >> T;
	while (T--) {
		char str[10];
		stack<int> num;
		stack<char> op;
		scanf("%s", str);
		int n = strlen(str);
		int ans = 0;
		for(int i = 0;i < n;i++){
			if(i % 2){
				if(op.size() && !(op.top() != 'x' && op.top() != '/' && (str[i] == 'x' || str[i] == '/'))  ){
					int y = num.top();
					num.pop();
					int x = num.top();
					num.pop();
					num.push(solve(x,y,op.top()));
					op.pop();
				}	
				op.push(str[i]);
			}
			else	num.push(str[i] - '0');
		}
		while(op.size()){
			int y = num.top();
			num.pop();
			int x = num.top();
			num.pop();
			num.push(solve(x,y,op.top()));
			op.pop();
		}
		if (num.top() == 24)	cout << "Yes" << endl;
		else
		{
			cout << "No" << endl;
		}
	}
	
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值