本文主要是介绍【CSP试题回顾】201903-2-二十四点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
CSP-201903-2-二十四点
关键点:中缀表达式转后缀表达式、后缀表达式计算
详见:【CSP考点回顾】后缀表达式计算/中缀表达式转后缀表达式
解题思路
-
将中缀表达式转换为后缀表达式。
-
计算后缀表达式的值:
-
主函数流程:首先读取一个整数n,表示有n个表达式需要判断。对于每个表达式,它首先将其转换为后缀形式,然后计算后缀表达式的值。如果结果等于24,就输出"Yes";否则,输出"No"。
完整代码
#include <iostream>
#include <stack>
#include <string>using namespace std;int getPriority(char c) { // 运算符的优先级if (c == 'x' || c == '/') return 2;return 1;
}// 中缀表达式转后缀表达式
string infixToPostfix(const string& infix) {string postfix;stack<char> opStack;for (char c : infix) {if (isdigit(c)) {postfix += c;}else{while (!opStack.empty() && getPriority(opStack.top()) >= getPriority(c)) {postfix += opStack.top();opStack.pop();}opStack.push(c);}}while (!opStack.empty()) { // 将栈内剩余的操作符添加到后缀表达式postfix += opStack.top();opStack.pop();}return postfix;
}int calculatePostfix(const string& postfix) { // 计算后缀表达式stack<int> valStack;for (char c : postfix) {if (isdigit(c)) {valStack.push(c - '0'); // 将字符转换为整数}else {int right = valStack.top(); valStack.pop();int left = valStack.top(); valStack.pop();switch (c) {case '+': valStack.push(left + right); break;case '-': valStack.push(left - right); break;case 'x': valStack.push(left * right); break;case '/': valStack.push(left / right); break;}}}return valStack.top();
}int n;
string expr, postfixExpr;int main() {cin >> n;for (int i = 0; i < n; i++){cin >> expr;postfixExpr = infixToPostfix(expr);if (calculatePostfix(postfixExpr) == 24) cout << "Yes\n";else cout << "No\n";}return 0;
}
这篇关于【CSP试题回顾】201903-2-二十四点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!