CCF CSP 201903-2 二十四点

#include <bits/stdc++.h>
#include <queue>
#include <iostream>
using namespace  std;
int main() {
    int n;
    string s;
    cin >> n;
    queue<int> num;
    queue<char> op;
    while(n--) {
        cin >> s;
        s.push_back('+');
        for(int i = 1; i < s.size(); i+=2) {
            int t = s[i-1] - '0';
            for ( ;i < s.size() && s[i] == 'x' || s[i] == '/'; i += 2) {
                t = (s[i] == 'x') ? t * (s[i+1]-'0'): t / (s[i+1] - '0');
            }
            num.push(t);
            op.push(s[i]);
        }
        num.push(0);
        int ans = num.front();
        num.pop();
        while(!op.empty()) {
            char opration = op.front();
            op.pop();
            ans = (opration == '+') ? ans + num.front() : ans - num.front();
            num.pop();
        }
        cout << (ans == 24 ? "Yes" : "No" )<< endl;
        //cout << ans;
    }
    return 0;
}

这个题目最一般的思路可能是按照数据结构课所学的,用后缀表达式,但是

https://blog.csdn.net/richenyunqi/article/details/89188626提出了这样的思路:

先算乘除,把表达式变成只有加减,然后计算加减即可。

(这体现了一种“减而治之”的思想——把大问题化简成小问题,把困难问题化简成简单问题)

具体思路见链接

posted @ 2019-08-17 19:38  明卿册  阅读(861)  评论(0编辑  收藏  举报