Cod sursa(job #2265880)

Utilizator SemetgTemes George Semetg Data 21 octombrie 2018 20:36:47
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <map>
using namespace std;

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

struct Token {
    int val;
    char op;
};

vector<Token> stivaPostfix;
char s[100005];
map<char, int> precedenta;

void transformaInPostfix() {
    vector<int> valori;
    vector<char> operatori;
    
    for (int i { 0 }; s[i]; ++i) {
        if (isdigit(s[i])) {
            int rez { 0 };
            while (isdigit(s[i]))
                rez = rez * 10 + s[i++] - '0';
            
            stivaPostfix.push_back({ rez, '\0' });
            --i;
        } else if (s[i] == '(') {
            operatori.push_back('(');
        } else if (s[i] == ')') {
            while (!operatori.empty() && operatori.back() != '(') {
                stivaPostfix.push_back({ -1, operatori.back() });
                operatori.pop_back();
            }
            
            operatori.pop_back();
        } else {
            while (!operatori.empty() && precedenta[operatori.back()] >= precedenta[s[i]]) {
                stivaPostfix.push_back({ -1, operatori.back() });
                operatori.pop_back();
            }
            
            operatori.push_back(s[i]);
        }
    }
    
    while (!operatori.empty()) {
        stivaPostfix.push_back({ -1, operatori.back() });
        operatori.pop_back();
    }
}

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

void calculeaza() {
    vector<int> stivaRezultat;
    for (auto& token : stivaPostfix) {
        if (token.val != -1) {
            stivaRezultat.push_back(token.val);
        } else {
            int val1 = stivaRezultat.back(); stivaRezultat.pop_back();
            int val2 = stivaRezultat.back(); stivaRezultat.pop_back();
            
            stivaRezultat.push_back(operatie(val2, val1, token.op));
        }
    }
    
    out << stivaRezultat.back();
}

int main() {
    in.getline(s, 100005);
    precedenta['*'] = precedenta['/'] = 3;
    precedenta['+'] = precedenta['-'] = 2;
    precedenta['('] = 1;
    
    transformaInPostfix();
    calculeaza();
}