【典中典】表达式树

· · 个人记录

AcWing 3302. 表达式求值(中缀表达式)

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;

char str[N];
unordered_map<char, short> prt{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; // priority of operators
stack<int> num;
stack<char> op;

inline void eval() {
    char c = op.top();
    op.pop();
    int b = num.top();
    num.pop();
    int a = num.top();
    num.pop();
    int x = 0;

    switch (c) {
        case '+': {
            x = a + b;
            break;
        }
        case '-': {
            x = a - b;
            break;
        }
        case '*': {
            x = a * b;
            break;
        }
        default: {
            x = a / b;
            break;
        }
    }

    num.push(x);
}

int main() {
    scanf("%s", str);
    int len = strlen(str);
    for (int i = 0; i < len; i++) {
        char c = str[i];
        if (isdigit(c)) {
            int x = 0, j = i;
            while (j < len && isdigit(str[j])) {
                x = x * 10 + str[j++] - '0';
            }
            i = j - 1;
            num.push(x);
        } else {
            if (c == '(') {
                op.push(c);
            } else if (c == ')') {
                while (op.top() != '(') {
                    eval();
                }
                op.pop();
            } else {
                while (op.size() && prt[op.top()] >= prt[c]) {
                    eval();
                }
                op.push(c);
            }
        }
    }
    while (op.size()) {
        eval();
    }
    printf("%d\n", num.top());
    return 0;
}

Luogu P7073 [CSP-J2020] 表达式(后缀表达式)

因为我当时爆零了于是鸽了