Cod sursa(job #1498283)

Utilizator DobosDobos Paul Dobos Data 8 octombrie 2015 11:43:55
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");
stack < char > oper;
stack < int > num;
string s;
inline void calcul()
{
    int b = num.top(); num.pop();
    int a = num.top(); num.pop();
    char semn = oper.top(); oper.pop();
    if(semn == '+') num.push(a+b);
    if(semn == '-') num.push(a-b);
    if(semn == '*') num.push(a*b);
    if(semn == '/') num.push(a/b);
}
inline int rangsemn(char s)
{
    if(s == '+' || s == '-')
        return 1;
    if(s== '*' || s == '/')
        return 2;
    return 0;
}

inline void evaloare()
{
    for(int i = 0; i < s.size(); i++)
    {
        if(s[i] == '('){
            oper.push('(');
        }
        else{
            if(s[i] == ')'){
                while(oper.top() != '(')
                    calcul();
                oper.pop();
            }
            else{
                int r = rangsemn(s[i]);
                if(r != 0){
                    while(rangsemn(oper.top()) >= r)
                        calcul();
                    oper.push(s[i]);
                }
                else{
                    int nr = 0;
                    for(; isdigit(s[i]); i++)
                        nr = nr * 10 + (s[i] - '0');
                    num.push(nr);
                    i--;
                }
            }
        }
    }
    while(oper.size() > 1)
        calcul();
}
int main()
{
    fin >> s;
    oper.push('#');
    evaloare();
    fout << num.top();
    return 0;
}