题意
题解
将中缀表达式转换为后缀表达式并同时计算。带变量的项当作多项式计算,方便起见,实现上加减法不对同类项合并系数,而是最后输出答案时同一合并。
class Solution {
public:
struct Var {
multiset<string> st;
int coef;
Var() : coef{0} {}
Var(int k) : coef{k} {}
Var(string s) : st{s}, coef{1} {}
Var operator*(Var& o) {
auto res = *this;
res.coef *= o.coef;
res.st.insert(o.st.begin(), o.st.end());
return res;
}
bool operator<(const Var& o) const {
if (st.size() != o.st.size()) {
return st.size() > o.st.size();
}
return st < o.st;
}
};
vector<Var> mul(vector<Var>& a, vector<Var>& b) {
vector<Var> res;
for (auto& x : a) {
for (auto& y : b) {
res.push_back(x * y);
}
}
return res;
};
vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {
map<string, int> val;
{
int n = evalvars.size();
for (int i = 0; i < n; ++i) {
val[evalvars[i]] = evalints[i];
}
}
map<char, int> rnk{{'(', -1}, {'+', 0}, {'-', 0}, {'*', 1}};
int n = expression.size();
vector<vector<Var>> vars;
vector<char> ops;
auto calc = [&](char op) {
assert(vars.size() >= 2);
auto b = vars.back();
vars.pop_back();
auto a = vars.back();
vars.pop_back();
if (op == '+' || op == '-') {
if (op == '-') {
for (auto& var : b) {
var.coef *= -1;
}
}
a.insert(a.begin(), b.begin(), b.end());
vars.push_back(a);
} else {
vars.push_back(mul(a, b));
}
};
for (int l = 0, r = 0; l < n; l = r) {
if (isdigit(expression[r])) {
int x = 0;
while (r < n && isdigit(expression[r])) {
x = x * 10 + expression[r] - '0';
r += 1;
}
vars.push_back({Var(x)});
} else if (isalpha(expression[r])) {
string s;
while (r < n && isalpha(expression[r])) {
s += expression[r];
r += 1;
}
if (val.count(s)) {
vars.push_back({Var(val[s])});
} else {
vars.push_back({Var(s)});
}
} else {
char op = expression[r + 1];
r += 3;
if (expression[r] == '(') {
ops.push_back(expression[r]);
} else if (expression[r] == ')') {
for (;;) {
auto op = ops.back();
ops.pop_back();
if (op == '(') {
break;
}
calc(op);
}
} else {
while (!ops.empty() && rnk[ops.back()] >= rnk[op]) {
calc(ops.back());
ops.pop_back();
}
ops.push_back(op);
}
}
}
while (!ops.empty()) {
calc(ops.back());
ops.pop_back();
}
map<Var, int> coef;
for (auto& var : vars[0]) {
coef[var] += var.coef;
}
vector<string> res;
for (auto [var, k] : coef) {
string s = to_string(k);
for (auto& t : var.st) {
s += "*" + t;
}
}
return res;
}
};