Cod sursa(job #2924320)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 29 septembrie 2022 16:51:31
Problema Evaluarea unei expresii Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>
using namespace std;

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

stack < char > op;
queue < pair < int , char > > q;
string s;
stack < int > rez;

bool accept(char a, char b) {
    if ((a=='+' || a=='-') && (b=='*' || b=='/')) return 1;
    if ((a=='+' || a=='-') && (b=='+' || b=='-')) return 1;
    if ((a=='*' || a=='/') && (b=='*' || b=='/')) return 1;
    return 0;
}

int calc(int x1, int x2, char w) {
    if (w=='+') return x1+x2;
    if (w=='-') return x1-x2;
    if (w=='*') return x1*x2;
    if (w=='/') return x1/x2;
    return 0;
}

void postfix() {
    int i=0;
    while (i<s.size()) {
        if (s[i]=='(') {
            op.push(s[i]);
            i++;
        }
        else if ('0'<=s[i] && s[i]<='9') {
            int x=0;
            while ('0'<=s[i] && s[i]<='9') {
                x = x*10+s[i]-'0';
                i++;
            }
            q.push({x,0});
        }
        else if (s[i]==')') {
            while (op.top()!='(') {
                q.push({0,op.top()});
                op.pop();
            }
            op.pop();
            i++;
        }
        else {
            while (accept(s[i],op.top())) {
                q.push({0,op.top()});
                op.pop();
            }
            op.push(s[i]);
            i++;
        }
    }
}

void solve() {
    while (!q.empty()) {
        pair < int , char > x = q.front();
        q.pop();
        if (x.first) rez.push(x.first);
        else {
            int x2=rez.top(); rez.pop();
            int x1=rez.top(); rez.pop();
            rez.push(calc(x1,x2,x.second));
        }
    }
    g << rez.top();
}

int main()
{
    f >> s;
    s = "(" + s + ")";
    postfix();
    solve();
    return 0;
}