Cod sursa(job #2988951)

Utilizator rARES_4Popa Rares rARES_4 Data 5 martie 2023 17:00:47
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <cstring>
using namespace std;
ifstream f ("evaluare.in");
ofstream g ("evaluare.out");
stack<int>numere;
stack<char>op;
char sir[100001];
int l;
int eval(int nr1,int nr2,char op)
{
    if(op=='+')
        return nr1+nr2;
    if(op=='*')
        return nr1*nr2;
    if(op=='-')
        return nr2-nr1;
    if(op=='/')
        return nr2/nr1;
}
int putere(char op)
{
    if(op=='+'||op=='-')
        return 1;
    if(op=='*' || op=='/')
        return 2;
    return 0;
}
int main()
{
    f >> sir;
    l = strlen(sir);
    for(int i = 0; i<l; i++)
    {
        if(sir[i]=='(')
        {
            op.push(sir[i]);
            continue;
        }
        if(isdigit(sir[i]))
        {
            int nr = 0;
            while(isdigit(sir[i]))
            {
                nr = nr*10+sir[i]-'0';
                i++;
            }
            i--;
            numere.push(nr);
            continue;
        }
        if(sir[i]==')')
        {
            while(!op.empty() && op.top()!='(')
            {
                int nr1 = numere.top();
                numere.pop();
                int nr2 = numere.top();
                numere.pop();
                char semn = op.top();
                op.pop();
                int nrnou = eval(nr1,nr2,semn);
                numere.push(nrnou);
            }
            op.pop();
            continue;
        }
        while(!op.empty() && putere(sir[i])<=putere(op.top()))
        {
                int nr1 = numere.top();
                numere.pop();
                int nr2 = numere.top();
                numere.pop();
                char semn = op.top();
                op.pop();
                int nrnou = eval(nr1,nr2,semn);
                numere.push(nrnou);
        }
        op.push(sir[i]);
    }
    while(!op.empty())
            {
                int nr1 = numere.top();
                numere.pop();
                int nr2 = numere.top();
                numere.pop();
                char semn = op.top();
                op.pop();
                int nrnou = eval(nr1,nr2,semn);
                numere.push(nrnou);
            }
        g << numere.top();
}