Cod sursa(job #2810897)

Utilizator DKMKDMatei Filibiu DKMKD Data 30 noiembrie 2021 15:45:55
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.52 kb
#include <bits/stdc++.h>
#define START ios_base::sync_with_stdio(false); fin.tie(NULL); fout.tie(NULL);
#define STOP fin.close(); fout.close();
#define N 1005

using namespace std;

ifstream fin("test.in");
ofstream fout("test.out");

int k;
char s[100005], aux[100005];
stack<char>S;
void citire() {

    fin >> s;
}

int precizie(char c) {

    if (c == '^')
        return 3;
    else if (c == '*' || c == '/')
        return 2;
    else if (c == '+' || c == '-')
        return 1;    

    return -1;
}

void solve() {

    int x = strlen(s);
    for (int i = 0; i < x; ++i) {
        char c = s[i];
        if (isalnum(c))
            aux[k++] = c;
        else if (c == '(')
            S.push('(');
        else if (c == ')') {
            while (S.top() != '(') {
                aux[k++] = S.top();
                S.pop();
            }
            S.pop();
        }
        else {
            aux[k++] = ' ';
            while (!S.empty() && precizie(c) <= precizie(S.top())) {
                aux[k++] = S.top();
                aux[k++] = ' ';
                S.pop();
            }
            S.push(c);
        }
    }
    aux[k++] = ' ';
    while (!S.empty()) {
        aux[k++] = S.top();
        aux[k++] = ' ';
        S.pop();
    }
}

void EvaluareExpresie() {

    solve();
    stack<long long>E;
    int x = strlen(aux);
    for (int i = 0; i < x; ++i) {
        if (aux[i] == ' ')
            continue;
        else if (isdigit(aux[i])) {
            long long nr = 0;
            while (isdigit(aux[i])) {
                nr = nr * 10 + (int)(aux[i] - '0');
                i++;
            }
            i--;
            E.push(nr);
        }
        else {
            long long val1=0, val2=0;
            if (!E.empty()) {
                val1 = E.top();
                E.pop();
            }
            if (!E.empty()) {
                val2 = E.top();
                E.pop();
            }
            if (aux[i] == '+')
                E.push(val1 + val2);
            else if (aux[i] == '-')
                E.push(abs(val1 - val2));
            else if (aux[i] == '*')
                E.push(1LL*val1 * val2);
            else {
                if (val1 >= val2)
                    E.push(val1 / val2);
                else
                    E.push(val2 / val1);
            }
                
        }
    }
    fout << E.top();
}

int main() {

    START;
    citire();
    EvaluareExpresie();
    STOP;
    return 0;
}