Cod sursa(job #2859337)

Utilizator gabriela.stanStan Luciana-Gabriela gabriela.stan Data 1 martie 2022 10:41:28
Problema Evaluarea unei expresii Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.22 kb
#include <bits/stdc++.h>

using namespace std;

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

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

char sir[100001];

void afish(stack<char>s1, stack<int>s2)
{
    cout<<"op: ";
    while(!s1.empty())
    {
        cout<<s1.top()<<" ";
        s1.pop();
    }
    cout<<endl<<"nr: ";
    while(!s2.empty())
    {
        cout<<s2.top()<<" ";
        s2.pop();
    }
    cout<<endl;
}

int prioritate(char c)
{
    if(c=='*' || c=='/') return 2;
    if(c=='+' || c=='-') return 1;
    return 0;
}

int eval(int a, int b, char c)
{
    switch(c)
    {
        case '+': return a+b;
        case '-': return a-b;
        case '*': return a*b;
        case '/': return a/b;
    }
    return 0;
}

void numar(int &x, int &i, char s[100001])
{
    while(isdigit(s[i]))
    {
        x=x*10+s[i]-'0';
        i++;
    }
    i--;
}

int c1(char s[100001])
{
    int n=strlen(s);
    for(int i=0; i<n; i++)
    {
        if(isdigit(s[i])) 
        {
            int x=0;
            numar(x, i, s);
            nr.push(x);
        }
        else if(s[i]=='(') op.push(s[i]);
        else if(s[i]==')')
        {
            while(!op.empty() && op.top()!='(')
            {
                int b=nr.top();
                nr.pop();
                int a=nr.top();
                nr.pop();
                char semn=op.top();
                op.pop();
                nr.push(eval(a, b, semn));
                afish(op, nr);
            }
            if(!op.empty()) op.pop();
        }
        else 
        {
            while(!op.empty() && (prioritate(op.top())>=prioritate(s[i])))
            {
                int b=nr.top();
                nr.pop();
                int a=nr.top();
                nr.pop();
                char semn=op.top();
                op.pop();
                nr.push(eval(a, b, semn));
                afish(op, nr);
            }
            op.push(s[i]);
        }
    }
    while(!op.empty())
    {
        int b=nr.top();
        nr.pop();
        int a=nr.top();
        nr.pop();
        char semn=op.top();
        op.pop();
        nr.push(eval(a, b, semn));
        afish(op, nr);
    }
    cout<<nr.top();
    return nr.top();
}

int main()
{
    f>>sir;
    g<<c1(sir);
    return 0;
}