Cod sursa(job #2302832)

Utilizator CyborgSquirrelJardan Andrei CyborgSquirrel Data 15 decembrie 2018 10:43:37
Problema Evaluarea unei expresii Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <iostream>
#include <stack>
#include <string>
#include <fstream>

using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

istream & in = fin;
ostream & out = fout;

stack<int> numbas;
stack<char> operators;

int GetPriority(char c)
{
    if(c == '+' || c == '-'){
        return 0;
    }else if(c == '*' || c == '/'){
        return 1;
    }else if(c == '('){
        return -1;
    }
}

bool IsNumba(char c)
{
    return (c >= '0' && c <= '9');
}

int ToNumba(char c)
{
    return (c - '0');
}

int Eval(char op, int a, int b)
{
    if(op == '+'){
        return a+b;
    }else if(op == '-'){
        return a-b;
    }else if(op == '*'){
        return a*b;
    }else if(op == '/'){
        return a/b;
    }
    return 0;
}

int Dijkstra(string s)
{
    char c;
    for(int i = 0; i < s.size(); i++){
        c = s[i];
        if(IsNumba(c)){
            int a = ToNumba(c);
            while(IsNumba(s[i+1])){
                a *= 10;
                a += ToNumba(s[i+1]);
                i++;
            }
            numbas.push(a);
        }else if(c == '('){
            operators.push(c);
        }else if(c == ')'){
            while(operators.top() != '('){
                int b = numbas.top();numbas.pop();
                int a = numbas.top();numbas.pop();
                numbas.push(Eval(operators.top(), a, b));
                operators.pop();
            }
            operators.pop();
        }else{
            while(!operators.empty() && GetPriority(operators.top()) > GetPriority(c)){
                int b = numbas.top();numbas.pop();
                int a = numbas.top();numbas.pop();
                numbas.push(Eval(operators.top(), a, b));
                operators.pop();
            }
            operators.push(c);
        }
    }
    while(!operators.empty()){
        int b = numbas.top();numbas.pop();
        int a = numbas.top();numbas.pop();
        numbas.push(Eval(operators.top(), a, b));
        operators.pop();
    }
    return numbas.top();
}

int main()
{
    string s;
    in >> s;
    out << Dijkstra(s);
    return 0;
}