Cod sursa(job #2886588)

Utilizator Mihai_EduardMihai Eduard Mihai_Eduard Data 7 aprilie 2022 21:48:43
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 kb
#include <bits/stdc++.h>

using namespace std;

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

int precedence(char op){
    if(op=='+' or op=='-')
        return 1;
    if(op=='*' or op=='/')
        return 2;
    return 0;
}

int applyOp(int a, int b, char op){
    switch(op){
        case '+': return a+b;
        case '-': return a-b;
        case '*': return a*b;
        case '/': return a/b;
    }
}

int evaluate(string s){
    stack<int> values;
    stack<char> ops;

    for(int i=0;i<s.size();i++){

        if(s[i]=='(')
            ops.push(s[i]);

        else if(isdigit(s[i])){
            int val=0;
            while(i<s.size() and isdigit(s[i])){
                val=val*10+(s[i]-'0');
                i++;
            }
            values.push(val);
            i--;
        }

        else if(s[i]==')'){
            while(!ops.empty() and ops.top()!='('){
                int val2=values.top();
                values.pop();
                int val1=values.top();
                values.pop();
                char op=ops.top();
                ops.pop();
                values.push(applyOp(val1,val2,op));
            }
            ops.pop();
        }

        else{
            while(!ops.empty() and precedence(ops.top())>=precedence(s[i])){
                int val2=values.top();
                values.pop();
                int val1=values.top();
                values.pop();
                char op=ops.top();
                ops.pop();
                values.push(applyOp(val1, val2, op));
            }
            ops.push(s[i]);
        }
    }

    while(!ops.empty()){
        int val2=values.top();
        values.pop();
        int val1=values.top();
        values.pop();
        char op=ops.top();
        ops.pop();
        values.push(applyOp(val1, val2, op));
    }

    return values.top();
}

int main() {
    string s;
    fin>>s;

    fout<<evaluate(s);

    fin.close();
    fout.close();
    return 0;
}