1 solutions

  • 0
    @ 2022-2-19 11:55:21

    求解前缀表达式值

    从后往前遍历前缀表达式,

    1. 遇到数字放入栈中。
    2. 遇到操作符,取出栈顶元素ta, tb,将操作完后的数放入栈
    3. 最后栈顶元素就是答案

    tips:这里用vector代替栈。另外,atof函数是将string转换成double Code:

    #include <bits/stdc++.h>
    #define ALL(a) (a).begin(), (a).end()
    using namespace std;
    using LL = long long;
    typedef pair<int, int> PII;
    template < typename T> inline void Max(T &a, T b) { if(a < b) a = b; }
    template < typename T> inline void Min(T &a, T b) { if(a > b) a = b; }
    
    int main() {
        cin.tie(nullptr) -> sync_with_stdio(false);
        string s;
        vector<string> a;
        vector<double> stk;
        while (cin >> s) a.push_back(s);
    
        for (int i = a.size() - 1; i >= 0; -- i) {
            if(a[i].size() == 1 && 
            (a[i][0] == '*' || a[i][0] == '/' || a[i][0] == '+' || a[i][0] == '-')) {
                double ta = stk.back(); stk.pop_back();
                double tb = stk.back(); stk.pop_back();
                if(a[i][0] == '+') stk.push_back(ta + tb);
                else if (a[i][0] == '/') stk.push_back(ta / tb);
                else if (a[i][0] == '*') stk.push_back(ta * tb);
                else {
                    stk.push_back(ta - tb);
                }
            } else {
                double x = atof(a[i].c_str());
                stk.push_back(x);
            }
        }
        printf("%.2f\n", stk.back());
        return 0;
    }
    
    • 1

    Information

    ID
    1498
    Time
    3000ms
    Memory
    128MiB
    Difficulty
    10
    Tags
    # Submissions
    2
    Accepted
    2
    Uploaded By