Cod sursa(job #2308287)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 26 decembrie 2018 19:36:46
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <stack>

using namespace std;

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

bool isoperator(char x) {
    if(x == '+' || x == '-' || x == '*' || x == '/')
        return 1;
    return 0;
}

int priority(char x) {
    if(x == '+' || x == '-')
        return 1;
    return 2;
}

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

int main() {
    string s;
    in >> s;

    stack<char> op;
    stack<int> values;
    for(int i = 0; i < s.size(); i ++) {
        char x = s[i];

        if(x == '(')
            op.push(x);
        else if(x == ')') {
            if(op.top() == '(')
                op.pop();
            else {
                while(op.top() != '(') {
                    int a = values.top();
                    values.pop();
                    int b = values.top();
                    values.pop();
                    values.push(compute(b, op.top(), a));

                    op.pop();
                }

                op.pop();
            }
        } else if(isoperator(x)) {
            while(op.size() && isoperator(op.top()) && priority(x) <= priority(op.top())) {
                int a = values.top();
                values.pop();
                int b = values.top();
                values.pop();
                values.push(compute(b, op.top(), a));

                op.pop();
            }

            op.push(x);
        } else {
            int nr = 0;
            while(i < s.size() && isdigit(s[i])) {
                nr *= 10;
                nr += (s[i] - '0');
                i ++;
            }
            if(i < s.size())
                i --;
            values.push(nr);
        }
    }

    while(op.size()) {
        int a = values.top();
        values.pop();
        int b = values.top();
        values.pop();
        values.push(compute(b, op.top(), a));

        op.pop();
    }

    out << values.top();

    return 0;
}