Cod sursa(job #1623084)

Utilizator lflorin29Florin Laiu lflorin29 Data 1 martie 2016 16:58:49
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.25 kb
#include <bits/stdc++.h>

using namespace std;

string s;
int prio[1234];

void makeOp() {
    prio['('] = prio[')'] = -22;
    prio['+'] = prio['-'] = 1;
    prio['*'] = prio['/'] = 2;
}

void get_nr (int &i, vector<char>&res) {
    for(; i < (int)s.size() && isdigit(s[i]); ++i)
       res.push_back(s[i]);
    res.push_back(',');
    i--;
}

void goleste(stack<char>&operatii, vector<char>&res) {
    while(!operatii.empty()) {
         char ce_op = operatii.top();
         if(ce_op == '(') break;
         operatii.pop();
         res.push_back(ce_op);
    }
    assert(operatii.size());
    operatii.pop();
}

void adauga(char ch , stack<char>&op, vector<char>&res) {
    while(!op.empty() && prio[ch] <= prio[op.top()])
        res.push_back(op.top()), op.pop();
    op.push(ch);
}

int ia_nr(vector<char>&res, int &i) {
    int x = 0;assert(isdigit(res[i]));
    for(; i<(int)res.size()&& isdigit(res[i]); ++i)
        x=x*10+res[i] - '0';
    --i;
    return x;
}

void fa_operatie(stack<int>&numere, char ch) {
    assert(numere.size()>1);
    int a = numere.top(); numere.pop();
    int b = numere.top(); numere.pop();
    swap(a, b);
    int rez;
    assert(ch=='+'||ch=='-'||ch=='/'||ch=='*');
    if(ch == '+') rez = a + b;
    else if(ch == '-') rez = a -b;
    else if(ch == '/') rez = a/b;
    else rez = a *b;
    numere.push(rez);
}

int eval() {
    makeOp();
    int n = s.size();

    stack<char>operatii;
    vector<char>res;

    for(int i = 0; i < n; ++i) {
    if(isdigit(s[i]))
        get_nr(i, res);
        else if(s[i] == '(') operatii.push('(');
        else if(s[i] == ')')
            goleste(operatii, res);
        else adauga(s[i], operatii, res);
    }

    while(!operatii.empty())
         res.push_back(operatii.top()), operatii.pop();

    stack<int>numere;
    for(int i=0; i < (int)res.size(); ++i) {
        char ch = res[i];
        if(isdigit(ch))
            numere.push(ia_nr(res, i));
        else if(ch == ',') continue;
        else{
             fa_operatie(numere, ch);
        }
    }

    return numere.top();

}

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

    fin >> s;
    fout << eval();
    return 0;
}