# 題目
zerojudge j607. 3. 先加後乘與函數
# 解題思路
目前沒東西...
# 程式碼
#include <bits/stdc++.h> | |
using namespace std; | |
#define int long long | |
string s; | |
pair<int, int> f(int idx); // 宣告 | |
pair<int, int> expre(int idx){ // Expression 計算 | |
stack<int> stk; | |
string op = "#"; // operators | |
while (idx < (int)s.size() && !(s[idx] == ',' || s[idx] == ')')){ | |
int temp = 0; | |
if (s[idx] == '+' || s[idx] == '*'){ | |
op = s[idx++]; | |
continue; | |
} | |
else if (s[idx] == 'f'){ | |
pair<int, int> buffer = f(idx + 2); //+2 後會是數字 | |
idx = buffer.first; | |
temp = buffer.second; | |
} | |
else{ | |
while (s[idx] >= 48 && s[idx] <= 57){ | |
temp *= 10; | |
temp += (s[idx++] - 48); | |
} | |
} | |
if (op == "+"){ // op[0]=='+' | |
temp += stk.top(); | |
stk.pop(); | |
stk.push(temp); | |
} | |
else if (op[0] == '*' && stk.size() >= 2){ | |
int ta = stk.top(); | |
stk.pop(); | |
ta *= stk.top(); | |
stk.pop(); | |
stk.push(ta); | |
stk.push(temp); | |
} | |
else stk.push(temp); | |
} | |
if (stk.size() >= 2){ | |
int ta = stk.top(); | |
stk.pop(); | |
ta *= stk.top(); | |
stk.pop(); | |
stk.push(ta); | |
} | |
return {idx, stk.top()}; | |
} | |
pair<int, int> f(int idx){ // 計算 f 函式 | |
pair<int, int> temp = expre(idx); | |
int mx, mn = temp.second; | |
mx = mn; | |
idx = temp.first; | |
while (s[idx++] != ')'){ // 注意這裡的 idx++ | |
temp = expre(idx); | |
idx = temp.first; | |
mx = max(mx, temp.second); | |
mn = min(mn, temp.second); | |
} | |
return {idx, (mx - mn)}; | |
} | |
signed main(){ | |
cin >> s; | |
cout << expre(0).second; | |
} |