Cod sursa(job #2705059)

Utilizator flibiaVisanu Cristian flibia Data 11 februarie 2021 20:27:50
Problema Evaluarea unei expresii Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <bits/stdc++.h>
#define ll long long 

using namespace std;

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

string s;

int priority(char op) {
    return 1 + (op != '+' && op != '-');
}

int evaluate(int a, int b, char op) {
    switch (op) {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            return a / b;
        default:
            return -1;
    }
}

string read(string &s, int &p) {
    string nr;
    while (p < s.size() && isdigit(s[p])) {
        nr += s[p++];
    }

    return nr;
}

int convert(string s) {
    stringstream read(s);
    int nr = 0;
    read >> nr;
    return nr;
}

vector<string> infix_to_postfix(string s) {
    vector<string> postfix;
    vector<string> operators;

    int p = 0;
    for (; p < s.size(); ) {
        if (isdigit(s[p])) {
            postfix.push_back(read(s, p));
        } else if (s[p] == '(') {
            operators.push_back(string(1, s[p++]));
        } else if (s[p] == ')') {
            while (operators.size() > 0 && operators.back() != "(") {
                postfix.push_back(operators.back());
                operators.pop_back();
            }
            
            operators.pop_back();
            p++;
        } else {
            while (operators.size() > 0 && operators.back() != "(" && priority(operators.back()[0]) >= priority(s[p])) {
                postfix.push_back(operators.back());
                operators.pop_back();
            }

            operators.push_back(string(1, s[p++]));
        }
    }

    while (operators.size() > 0) {
        postfix.push_back(operators.back());
        operators.pop_back();
    }

    return postfix;
}

int evaluate_postfix(vector<string> v) {
    vector<int> operands;
    int ans = 0, a, b;

    for (auto it : v) {
        if (isdigit(it[0])) {
            operands.push_back(convert(it));
        } else {
            b = operands.back();
            operands.pop_back();
            a = operands.back();
            operands.pop_back();

            operands.push_back(evaluate(a, b, it[0]));
        }
    }

    return operands[0];
}

int main() {
    in >> s;

    out << evaluate_postfix(infix_to_postfix(s));

    return 0;
}