Pagini recente » Cod sursa (job #1196893) | Cod sursa (job #1039060) | Cod sursa (job #2450689) | Cod sursa (job #375241) | Cod sursa (job #2988630)
#include <iostream>
#include <fstream>
#include <stack>
#include <cstring>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char expr[100002];
stack < int > opz; /// operanzi
stack < char > opt; /// operatori
int get_priority(char op){
if(op == '+' || op == '-'){
return 1;
}
if(op == '*' || op == '/'){
return 2;
}
return 0;
}
int eval_expr(int op1, int op2, char op){
if(op == '+'){
return op1 + op2;
}
if(op == '-'){
return op1 - op2;
}
if(op == '*'){
return op1 * op2;
}
return op1 / op2;
}
void solve_last_operation(){
char oprtor = opt.top();
opt.pop();
int operand2 = opz.top();
opz.pop();
int operand1 = opz.top();
opz.pop();
int res = eval_expr(operand1, operand2, oprtor);
///cout << operand1 << " " << op2 << " " << op << " -> ";
opz.push(res);
}
void solve_parenthesis(){
while(opt.top() != '('){
solve_last_operation();
}
opt.pop();
}
int main()
{
fin >> expr;
int len = strlen(expr);
expr[len] = ')';
expr[len + 1] = 0;
opt.push('(');
for(int i = 0; i <= len; i++){
if(expr[i] == '('){
opt.push(expr[i]);
}else if(expr[i] == ')'){
solve_parenthesis();
}else if(isdigit(expr[i])){
if(i > 0 && isdigit(expr[i - 1])){
int top_stack = opz.top();
opz.pop();
int new_number = top_stack * 10 + (expr[i] - '0');
opz.push(new_number);
}else{
opz.push(expr[i] - '0');
}
}else{
if(opt.top() == '('){
opt.push(expr[i]);
}else{
while(get_priority(expr[i]) <= get_priority(opt.top())){
solve_last_operation();
}
opt.push(expr[i]);
}
}
}
fout << opz.top();
return 0;
}