Cod sursa(job #2157779)

Utilizator savigunFeleaga Dragos-George savigun Data 9 martie 2018 21:55:38
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <string.h>
#include <vector>
using namespace std;

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

int n, pr[256], id[5];
char s[100005];
stack<char> op;
stack<int> ev;
vector<int> polo;

int get_number(int &i) {
    int nr = 0;
    while (i < n && isdigit(s[i])) {
        nr = nr * 10 + (s[i] - '0');
        i++;
    }
    i--;
    return nr;
}

void push_op_in_polo() {
    polo.push_back(id[op.top()]);
    op.pop();
}

int main()
{
    pr['+'] = pr['-'] = 1;
    pr['*'] = pr['/'] = 2;
    pr['('] = 0;

    id['+'] = -1;
    id['-'] = -2;
    id['*'] = -3;
    id['/'] = -4;

    in >> s;
    n = strlen(s);

    for (int i = 0; i < n; ++i) {
        if (isdigit(s[i])) {
            polo.push_back(get_number(i));
        } else if (s[i] == '(') {
            op.push('(');
        } else if (s[i] == ')') {
            while (op.top() != '(') push_op_in_polo();
            op.pop();
        } else {
            while (!op.empty() && pr[s[i]] <= pr[op.top()])  push_op_in_polo();
            op.push(s[i]);
        }
    }

    while (!op.empty()) push_op_in_polo();

    for (int i = 0; i < polo.size(); ++i) {
        if (polo[i] >= 0) ev.push(polo[i]);
        else {
            int b = ev.top(); ev.pop();
            int a = ev.top(); ev.pop();
            int r = 0;

            if (polo[i] == -1) {
                r = a + b;
            } else if (polo[i] == -2) {
                r = a - b;
            } else if (polo[i] == -3) {
                r = a * b;
            } else {
                r = a / b;
            }

            ev.push(r);
        }
    }

    out << ev.top();


    return 0;
}