Cod sursa(job #2830489)

Utilizator NeuerRaducu Ioan Stefan Neuer Data 9 ianuarie 2022 22:57:01
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
///#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stack>
#include <cstring>

using namespace std;
const int SIZE = 1e5+10;

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

int n;
char s[SIZE];
int post[SIZE], pn;
stack <int> stck;
int rezcnt;

/// * / + -


void postord()
{
    int ord;
    for(int i=0; i<n; i++)
    {
        ord = 0;
        if('0'<=s[i] && s[i]<='9') {
            post[++pn] = atoi(s+i);
            while('0'<=s[i] && s[i]<='9') i++;
            i--;
        }
        else if(s[i]=='(') ord = -10;
        else if(s[i]=='*') ord = -4;
        else if(s[i]=='/') ord = -3;
        else if(s[i]=='+') ord = -2;
        else if(s[i]=='-') ord = -1;
        else if(s[i]==')') ord = -11;
        if(ord==-11) {
            while(stck.top()!=-10)
                post[++pn] = stck.top(), stck.pop();
            stck.pop();
        }
        else if(ord==-10) stck.push(-10);
        else if(ord) {
            while(!stck.empty() && stck.top()!=-10 && (stck.top()<=ord || (ord-1)/2==(stck.top()-1)/2)) {
                post[++pn] = stck.top();
                stck.pop();
            }
            stck.push(ord);
        }
    }
    while(!stck.empty())
        post[++pn] = stck.top(), stck.pop();
}

int rez()
{
    if(post[rezcnt]<-4 || post[rezcnt]>=0) return post[rezcnt--];
    int op = post[rezcnt--], t1, t2;
    t2 = rez(), t1 = rez();
    if(op==-1) return t1-t2;
    if(op==-2) return t1+t2;
    if(op==-3) return t1/t2;
    return t1*t2;
}

int main()
{
    cin>>s;
    n=strlen(s);
    postord();
    rezcnt = pn;
    cout<<rez();
    return 0;
}