Pagini recente » Cod sursa (job #622210) | Cod sursa (job #233571) | Cod sursa (job #85826) | Cod sursa (job #2810118) | Cod sursa (job #2969957)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pb push_back
#define mp make_pair
#define f first
#define s second
int precedence(char op){
if(op == '+' || op == '-')
return 1;
if(op == '*' || op == '/')
return 2;
return 0;
}
int applyOp(int a, int b, char op){
switch(op){
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
}
}
int evaluate(string tokens){
stack<int> values;
stack<int> ops;
for(int i = 0; i < tokens.size(); i++){
if(tokens[i] == '(')
ops.push(tokens[i]);
else if(isdigit(tokens[i])){
int val = 0;
while(i < tokens.size() && isdigit(tokens[i])){
val = val * 10 + (tokens[i] - 48);
i++;
}
values.push(val);
i--;
} else if(tokens[i] == ')'){
while(!ops.empty() && ops.top() != '('){
int val2 = values.top(); values.pop();
int val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOp(val1, val2, op));
}
if(!ops.empty())
ops.pop();
} else {
while(!ops.empty() && precedence(ops.top()) >= precedence(tokens[i])){
int val2 = values.top(); values.pop();
int val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOp(val1, val2, op));
}
ops.push(tokens[i]);
}
}
while(!ops.empty()){
int val2 = values.top(); values.pop();
int val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOp(val1, val2, op));
}
return values.top();
}
void solve(){
string s;
cin >> s;
cout << evaluate(s) << '\n';
}
int main(){
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
ios::sync_with_stdio(0); cin.tie(0);
int t = 1;
//cin >> t;
while(t--){
solve();
}
}