201903-2 二十四点数

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm>
#include <stack>
#include <map>
// 嫌弃太长,直接使用
// #include <bits/stdc++.h>

using namespace std;

stack<int> num;
stack<char> ops;
map<char, int> prio; // priority

void compute() {
    
    
	int num1 = num.top();
	num.pop();
	int num2 = num.top();
	num.pop();
	char op = ops.top();
	ops.pop();
	switch (op) {
    
    
		case 'x':
			num.push(num2 * num1);
			break;
		case '/':
			num.push(num2 / num1);
			break;
		case '+':
			num.push(num2 + num1);
			break;
		case '-':
			num.push(num2 - num1);
			break;
	}
}

int main() {
    
    
//	freopen("in.txt", "r", stdin);
	prio['+'] = prio['-'] = 0;
	prio['x'] = prio['/'] = 1;

	int n;
	cin >> n;

	for (int i = 1; i <= n; i++) {
    
    
		string s;
		cin >> s;
		num.push(s[0] - '0');
		ops.push(s[1]);
		num.push(s[2] - '0');

		for (int j = 3; j < s.length(); j++) {
    
    
			// 如果是数字,直接入操作数栈
			if (s[j] >= '0' && s[j] <= '9') {
    
    
				num.push(s[j] - '0');
			} else {
    
      // 如果是操作符
				// 当前操作符比栈顶操作符的优先级低或者等
				while (!ops.empty() && prio[s[j]] <= prio[ops.top()]) {
    
    
					compute();
				}
				
				// 当前操作符比栈顶操作符的优先级高,直接入栈。
				ops.push(s[j]);
			}
		}

		while (!ops.empty())
			compute();
		printf(num.top() == 24 ? "Yes\n" : "No\n");
		num.pop();
	}

	return 0;
}
/**

10
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
1x1+9-9
1x9-5/9
8/5+6x9
6x7-3x6
6x4+4/5

*/

参考1

猜你喜欢

转载自blog.csdn.net/qq_40750972/article/details/114416280
今日推荐