Cod sursa(job #2857419)

Utilizator gabriela.stanStan Luciana-Gabriela gabriela.stan Data 25 februarie 2022 16:10:38
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <bits/stdc++.h>

using namespace std;

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

stack <int> nr;
stack <char> op;

char sir[100001];

void eval()
{
    int x=nr.top();
    nr.pop();
    int y=nr.top();
    nr.pop();
    char c;
    c=op.top();
    op.pop();
    // cout<<'\n'<<"op: "<<(char)c<<'\n';
    if(c=='+') nr.push(x+y);
    else if(c=='-') nr.push(y-x);
    else if(c=='*') nr.push(y*x);
    else nr.push(y/x);
    //cout<<"x="<<x<<'\n'<<"y="<<y<<'\n'<<"nr="<<nr.top()<<'\n'<<'\n';
}

void print(stack<int> nr, stack<char> op) 
{
    cout << "nr: ";
    while (!nr.empty()) 
    {
        cout << nr.top() << " ";
        nr.pop();
    }
    cout << "\nop:";
    while (!op.empty()) 
    {
        cout << op.top() << " ";
        op.pop();
    }
    cout << "\n";
}

int rez(char s[100005], int k)
{
    int n=k;
    for(int i=0; i<n; i++)
    {
        if(isdigit(s[i]))
        {
            int x=0;
            while(i<n && isdigit(s[i]))
            {
                x=x*10+s[i]-'0';
                i++;
            }
            i--;
            nr.push(x);
            // cout<<"x= "<<x<<'\n';
        }
        else if(s[i]=='(') op.push(s[i]);
        else if(s[i]==')' && !op.empty())
        {
            if(op.top()=='(') op.pop();
            else 
            {
                while(op.top()!='(') eval();
                op.pop();
            }
        }
        else if(op.empty()) op.push(s[i]);
        else if(s[i]=='*')
        {
            while(!op.empty() && op.top()=='/') eval();
            op.push(s[i]);
        }
        else if(s[i]=='/')
        {
            while(!op.empty() && (op.top()=='*' || op.top()=='/')) eval();
            op.push(s[i]);
        }
        else if(s[i]=='-')
        {
            while(!op.empty() && (op.top()=='*' || op.top()=='/' || op.top()=='-')) eval();
            op.push(s[i]);
        }
        else if(s[i]=='+')
        {
            while(!op.empty() && (op.top()=='*' || op.top()=='/' || op.top()=='-')) eval();
            op.push(s[i]);
        }
        print(nr, op);
    }
    while(!op.empty()) eval();
    return nr.top();
}

int main()
{
    f>>sir;
    g<<rez(sir, strlen(sir));
    return 0;
}