Cod sursa(job #2690335)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 23 decembrie 2020 16:56:00
Problema Evaluarea unei expresii Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

using namespace std;

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

char ss[100001];

int main(){

    f >> ss;
    stack <int> st, ops;

    for(int i = 0;ss[i];){

        if(isdigit(ss[i])){
            int Nr = 0;
            while(isdigit(ss[i]))
                Nr = Nr * 10 + (ss[i] - '0'), i++;
            st.push(Nr);
            i--;
        }

        if(ss[i] == '+') {i++; ops.push(1); continue;}
        if(ss[i] == '-') {i++; ops.push(2); continue;}
        if(ss[i] == '*') {i++; ops.push(3); continue;}
        if(ss[i] == '/') {i++; ops.push(4); continue;}
        if(ss[i] == '(') {i++; ops.push(5); continue;}

        if(ss[i] == ')') {
            while(ops.top() != 5){
                int Nr = st.top();
                st.pop();
                if(ops.top() == 1) st.top() += Nr;
                if(ops.top() == 2) st.top() -= Nr;
                ops.pop();
            }
            ops.pop();
        }


        while(!ops.empty() && (ops.top() == 3 || ops.top() == 4)){

            int Nr = st.top();
            st.pop();
            if(ops.top() == 3) st.top() *= Nr;
            if(ops.top() == 4) st.top() /= Nr;
            ops.pop();
        }
        i++;
    }


    while(st.size() > 1){
        int Nr = st.top();
        st.pop();
        if(ops.top() == 1) st.top() += Nr;
        if(ops.top() == 2) st.top() -= Nr;
        ops.pop();
    }

    g << st.top();

}