Cod sursa(job #3208302)

Utilizator andreea678Rusu Andreea-Cristina andreea678 Data 28 februarie 2024 10:53:39
Problema Evaluarea unei expresii Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.74 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <cstring>


using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
void afisare (stack<int> s2){
    while (!s2.empty()){
        cout<<s2.top()<< ' ';
        s2.pop();
    }
    cout << '\n';
}
int main()
{
    char sir[100005];
    bool afost=false;
    stack<char>s1;
    stack<pair<int,char>>s2;
    stack<int> numere;
    stack<pair<int,char>> invers;
    int nr=0;
    fin >> sir;
    for (int i=0; sir[i]; ++i){
        if(sir[i]=='('){
            s1.push('(');
        }

        if (isdigit(sir[i])){
            nr=nr*10+(int)sir[i]-'0';
            afost=true;
        }

        if (afost==true && !isdigit(sir[i])){
            afost=false;
            s2.emplace(nr,0);
            nr=0;
        }

        if (sir[i]=='+' || sir[i]=='-'){
            while(!s1.empty() && (s1.top()=='*' || s1.top()=='/')){
                s2.emplace(0,s1.top());
                s1.pop();
            }
            s1.push(sir[i]);

        }

        if (sir[i]==')'){
            while (!s1.empty() && s1.top()!='('){
                s2.emplace(0,s1.top());

                s1.pop();

            }
            ///8/4*2
            if(!s1.empty())
                s1.pop();

        }

        if (sir[i]=='*'){
            while(!s1.empty() && s1.top()=='/'){
                s2.emplace(0,s1.top());
                s1.pop();
            }
            s1.push(sir[i]);
        }
        if (sir[i]=='/'){
            s1.push(sir[i]);
        }
        /// (1+1)*13+10/2
    }
    if (afost==true){
        s2.emplace(nr,0);
    }
    while(!s1.empty()){
        s2.emplace(0,s1.top());
        s1.pop();
    }
    while (!s2.empty()){
        if (s2.top().second==0){
            invers.emplace(s2.top().first,0);
        }
        else{
            invers.emplace(0,s2.top().second);
        }
        s2.pop();
    }
    while(!invers.empty()){
        if (invers.top().second==0){
            numere.push(invers.top().first);
        }
        else {
            int nr1=numere.top();
            numere.pop();
            int nr2=numere.top();
            numere.pop();
            if (invers.top().second=='+'){
               numere.push(nr1+nr2);
            }
            if (invers.top().second=='-'){
                numere.push(nr2-nr1);
            }
            if (invers.top().second=='/'){
                numere.push(nr2/nr1);
            }
            if (invers.top().second=='*'){
                numere.push(nr2*nr1);
            }
        }
        afisare(numere);
        invers.pop();
    }



    cout << '\n';
    fout << numere.top();
    return 0;
}