Cod sursa(job #2166181)

Utilizator andrei.gramescuAndrei Gramescu andrei.gramescu Data 13 martie 2018 15:56:12
Problema Evaluarea unei expresii Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.52 kb
#include <cstdio>
#include <vector>
#include <stack>
#include <cstring>
#include <ctype.h>
using namespace std;
#define NMAX 100005

char s[NMAX], c, top;
bool frecv[NMAX * 4];
vector<int> expr;
vector<char> op;
stack<int> st;

int priorityOf(char token) {
    if(token == '(')
        return 0;
    if(token == '+' || token == '-')
        return 1;
    if(token == '*' || token == '/')
        return 2;
}

int main(){

    int aux = 0, i, n;
    int a, b, rez;
    FILE *fin, *fout;
    fin = fopen("evaluare.in", "r");
    fout = fopen("evaluare.out", "w");

    fscanf(fin, "%s", s);
    n = strlen(s);
    for(i=0; i<n; i++) {
        c = s[i];

        if(isdigit(c)) {
            if(!aux)
                aux = c - 48;
            else {
                aux *= 10;
                aux += (c - 48);
            }
        }
        else {
            if(aux) {
                expr.push_back(aux);
                aux = 0;
            }

            if(!op.empty())
                top = op.back();

            if(c == ')') {
                while(top != '(') {
                       expr.push_back(top);
                       frecv[ expr.size() - 1 ] = true;
                       op.pop_back();
                       top = op.back();
                }
                op.pop_back();
                continue;
            }

            if(c == '(') {
                op.push_back(c);
                continue;
            }

            while(priorityOf(c) <= priorityOf(top)) {
                expr.push_back(top);
                frecv[ expr.size() - 1 ] = true;
                op.pop_back();
                if(!op.empty())
                    top = op.back();
                else top = 0;
            }
            op.push_back(c);
        }
    }

    if(aux)
        expr.push_back(aux);

    while(!op.empty()) {
        top = op.back();
        expr.push_back(top);
        frecv[ expr.size() - 1 ] = true;
        op.pop_back();
    }

    n = (int) expr.size();

    for(i=0; i<n; i++) {
        if(!frecv[i])
            st.push(expr[i]);
        else {
            c = (char) expr[i];
            a = st.top(); st.pop();
            b = st.top(); st.pop();

            if(c == '+') rez = b + a;
            else if(c == '-') rez = b - a;
            else if(c == '/') rez = b / a;
            else if(c == '*') rez = b * a;

            st.push(rez);
        }
    }

    rez = st.top();
    fprintf(fout, "%d", rez);
    return 0;
}