Cod sursa(job #1505400)

Utilizator SirStevensIonut Morosan SirStevens Data 19 octombrie 2015 09:15:55
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#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;
}