Cod sursa(job #2843990)

Utilizator Radu_MocanasuMocanasu Radu Radu_Mocanasu Data 3 februarie 2022 15:38:39
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
stack <char> op;
stack <int> polo;
char s[100001];
int prior(char op){
    switch(op){
        case '+' : return 1;
        case '-' : return 1;
        case '*' : return 2;
        case '/' : return 2;
    }
    return 0;
}
int oper(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 main()
{
    char x;
    int a,b,n = 0,i,j,t;
    cin.getline(s,100001);
    t = strlen(s);
    for(i = 0; i < t; ++i){
        if(isdigit(s[i])){
            n = 0;
            while(i < t && isdigit(s[i])){
                n = (n * 10) + (s[i] - '0');
                ++i;
            }
            polo.push(n);
            i--;
        }
        if(s[i] == '('){
            op.push(s[i]);
        }
        if(s[i] == ')'){
            while(!op.empty() && op.top() != '('){
                x = op.top();
                op.pop();
                a = polo.top();
                polo.pop();
                b = polo.top();
                polo.pop();
                polo.push(oper(b,a,x));
            }
            if(!op.empty()){
                op.pop();
            }
        }
        if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){
            while(!op.empty() && prior(s[i]) <= prior(op.top())){
                x = op.top();
                op.pop();
                a = polo.top();
                polo.pop();
                b = polo.top();
                polo.pop();
                polo.push(oper(b,a,x));
            }
            op.push(s[i]);
        }
    }
    while(!op.empty()){
        x = op.top();
        op.pop();
        a = polo.top();
        polo.pop();
        b = polo.top();
        polo.pop();
        polo.push(oper(b,a,x));
    }
    cout << polo.top();
    return 0;
}