dalao们,这是我的代码,请指教
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <stack>
#include <cstdio>
#define ll long long
using namespace std;
string s;
vector<ll> a;
stack<char> b;
int more(char c){
switch(c){
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
case '^': return 3;
case '(': return 0;
case ')': return 0;
default: return -1;
}
}
ll calculate(ll a, ll b, char op){
if(op == '+') return a + b;
if(op == '-') return a - b;
if(op == '*') return a * b;
if(op == '/') return a / b;
if(op == '^'){
ll ans = 1;
for(int i = 1; i <= b; i++) ans *= a;
return ans;
}
return (-1 << 30);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> s;
for(int i = 0; i < s.size(); i++){
if(s[i] >= '0' && s[i] <= '9') a.push_back((ll)(s[i] - '0'));
else{
if(b.empty() || s[i] == '^') b.push(s[i]);
else if(more(s[i]) > more(b.top()) || s[i] == '('){
b.push(s[i]);
continue;
}
else{
ll t = more(s[i]);
if(s[i] == ')'){
while(!b.empty() && b.top() != '(') a.push_back((ll)(b.top() - '0')), b.pop();
b.pop();
continue;
}
while(!b.empty() && t <= more(b.top())) a.push_back((ll)(b.top() - '0')), b.pop();
b.push(s[i]);
}
}
}
while(!b.empty()) a.push_back((ll)(b.top() - '0')), b.pop();
while(a.size() > 1){
vector<ll>::iterator it;
for(it = a.begin(); it != a.end(); it++){
if(*it < 0 || *it + '0' == 94) cout << (char)(*it + '0');
else cout << *it;
cout << ' ';
}
cout << "\n";
for(it = a.begin(); it != a.end(); it++)
if(*it < 0 || *it + '0' == 94){
ll tmp = (ll)(calculate(*(it - 2), *(it - 1), (char)(*it + '0')));
a.insert(it + 1, tmp);
a.erase(it - 2, it + 1);
break;
}
}
cout << a[0] << "\n";
return 0;
}