Cod sursa(job #2976256)

Utilizator Octavian1705octavian lupu Octavian1705 Data 8 februarie 2023 19:25:49
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.41 kb
#include <fstream>
#include <cctype>
#include <cstring>
#include <stack>

using namespace std;

ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");

const int NMAX=100001;
char s[NMAX];

stack<int>polo;
stack<char>op;

int calcul (int a, int b, char ch)
{
    switch (ch)
    {
    case '+':
        return a+b;
    case '-':
        return a-b;
    case '*':
        return a*b;
    case '/':
        return a/b;
    }
}

int prior (char ch)
{
    switch(ch)
    {
    case '+':
        return 1;
    case '-':
        return 1;
    case '*':
        return 2;
    case '/':
        return 2;
    }
    return 0;
}

int main()
{
    int n,i,x,a,b,c;
    char ch;
    fin.getline(s,NMAX);
    n=strlen(s);
    x=0;
    i=0;
    while (i<n)
    {
        if (isdigit(s[i]))
        {
            x=x*10+s[i]-'0';
            i++;
            while(i<n && isdigit(s[i]))
            {
                x=x*10+s[i]-'0';
                i++;
            }
            polo.push(x);
            x=0;
            continue;
        }
        if (s[i]=='(')
        {
            op.push('(');
            i++;
            continue;
        }
        if (s[i]=='+' || s[i]=='-' || s[i]=='/' || s[i]=='*')
        {
            if (op.empty() || op.top()=='(' || prior(op.top())<prior(s[i]))
                op.push(s[i]);
            else
            {
                while (!op.empty() && prior(op.top())>=prior(s[i]))
                {
                    ch=op.top();
                    op.pop();
                    b=polo.top();
                    polo.pop();
                    a=polo.top();
                    polo.top()=calcul(a,b,ch);
                }
                op.push(s[i]);
            }
            i++;
            continue;
        }
        if (s[i]==')')
        {
            while (!op.empty() && op.top()!='(')
            {
                ch=op.top();
                op.pop();
                b=polo.top();
                polo.pop();
                a=polo.top();
                polo.top()=calcul(a,b,ch);
            }
            op.pop();
            i++;
            continue;
        }
    }
    while (!op.empty())
    {
        ch=op.top();
        op.pop();
        b=polo.top();
        polo.pop();
        a=polo.top();
        polo.top()=calcul(a,b,ch);
    }
    fout<<polo.top();
    return 0;
}