【CSP试题回顾】201903-2-二十四点(优化)

本文介绍了一段C++代码,用于将中缀表达式转换为后缀表达式,并利用后缀表达式计算得到24点问题的结果。该程序通过栈实现运算符处理和计算。
摘要由CSDN通过智能技术生成

CSP-201903-2-二十四点

解题代码

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <stack>
#include <string>
using namespace std;

// 检查字符是否是操作符
bool isOperator(char c) {
    return c == '+' || c == '-' || c == 'x' || c == '/';
}

// 检查运算符的优先级
int getPriority(char c) {
    if (c == 'x' || c == '/') return 2;
    if (c == '+' || c == '-') return 1;
    return 0;
}

// 中缀表达式转后缀表达式
string infixToPostfix(const string& infix) {
    string postfix;
    stack<char> opStack;

    for (char c : infix) {
        if (c == ' ') continue; // 忽略空格
        if (isdigit(c)) {
            postfix += c;
        }
        else if (c == '(') {
            opStack.push(c);
        }
        else if (c == ')') {
            while (!opStack.empty() && opStack.top() != '(') {
                postfix += opStack.top();
                opStack.pop();
            }
            opStack.pop(); // 弹出 '('
        }
        else if (isOperator(c)) {
            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;

int main()
{
    cin >> n;
    for (size_t i = 0; i < n; i++)
    {
        cin >> expr;
        if (calculatePostfix(infixToPostfix(expr))==24)
            cout << "Yes\n";
        else
            cout << "No\n";
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值