Pagini recente » Cod sursa (job #768882) | Cod sursa (job #2900049) | Cod sursa (job #2229136) | Cod sursa (job #69708) | Cod sursa (job #2893415)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");
string s;
stack<ll>st;
stack<char>op;
bool is_op (char ch){
return (ch == '-' || ch == '*' || ch == '+' || ch == '/');
}
void process(stack<ll> &st , char op){
ll r = st.top(); st.pop();
ll l = st.top(); st.pop();
switch (op){
case '+' : st.push(l + r); break;
case '-' : st.push(l - r); break;
case '*' : st.push(l * r); break;
case '/' : st.push(l / r); break;
}
}
int priority (char op){
if (op == '+' || op == '-'){
return 1;
}
if (op == '*' || op == '/'){
return 2;
}
return 0;
}
ll evaluate (string &s){
for (int i=0; i<(int)s.size(); i++){
if (s[i] == ' '){
continue;
}
if (s[i] == '('){
op.push(s[i]);
}
else if (s[i] == ')'){
while (op.top() != '('){
process(st , op.top());
op.pop();
}
op.pop();
}
else if (is_op(s[i])){
char cur_op = s[i];
while (!op.empty() && priority(op.top()) >= priority(cur_op)){
process(st , op.top());
op.pop();
}
op.push(cur_op);
}
else{
ll number = 0;
while (i < (int)s.size() && isdigit(s[i])){
number = number * 10 + (s[i] - '0');
i += 1;
}
--i;
st.push(number);
}
}
while (!op.empty()){
process(st , op.top());
op.pop();
}
return st.top();
}
int main(){
ios_base::sync_with_stdio(false);
fin >> s;
fout << evaluate(s);
}