Pagini recente » Cod sursa (job #910491) | Cod sursa (job #2798598) | Cod sursa (job #3175636) | Cod sursa (job #1326605) | Cod sursa (job #1505400)
#include <bits/stdc++.h>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
const int Nmax= 1e5 +5 ;
char S[Nmax];
stack <char> ops;
stack <int> nums;
inline void Operation()
{
char op = ops.top();ops.pop();
int b =nums.top();nums.pop();
int a = nums.top();nums.pop();
if(op == '+') nums.push(a+b);
if(op == '-') nums.push(a-b);
if(op == '*') nums.push(a*b);
if(op == '/') nums.push(a/b);
}
inline int Priority(char &c)
{
if(c == '+' || c == '-') return 1;
if(c == '*' || c == '/') return 2;
return 0;
}
inline void Evaluate(){
ops.push('$');
int n = strlen(S);
int x, p;
for(int i = 0; i < n; i++){
if(S[i] == '('){
ops.push(S[i]);
} else {
if(S[i] == ')'){
while(ops.top() != '('){
Operation();
}
ops.pop();
} else {
p = Priority(S[i]);
if(p){
while(Priority(ops.top()) >= p){
Operation();
}
ops.push(S[i]);
} else {
x = 0;
while(isdigit(S[i])){
x = x * 10 + (S[i] - '0');
i++;
}
i--;
nums.push(x);
}
}
}
}
while(ops.size() > 1){
Operation();
}
}
int main()
{
in>>S;
Evaluate();
out<<nums.top();
return 0;
}