Cod sursa(job #2562565)

Utilizator serafimalex2001Serafim Alex serafimalex2001 Data 29 februarie 2020 15:37:06
Problema Evaluarea unei expresii Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.51 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <cstring>
#define plus 2000000000
#define minus 2000000001
#define div 2000000002
#define  mult 2000000003
#define paran 2000000004
#define stop  2000000005
using namespace std;

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

char s[100009];
int n;
int gt;

stack<int> S, Result;

void Read()
{
    int i,j;
    fin>>s;
    n = strlen(s);
}

int Number(int &i)
{
    int nr = 0;
    int p = 1;
    while(isdigit(s[i]))
    {
        nr = nr*10 + s[i]-'0';
        ++i;
    }
    return nr;
}

int Eval()
{
    int total = 0;
    int x1,x2;
    int op;
    while(S.top() != paran)
    {
        x1 = S.top();
        S.pop();
        op = S.top();
        S.pop();
        if(op == plus)
        {
            total += x1;
        }
        if(op == minus)
            total -= x1;
        if(op == div)
        {
            x2 = S.top();
            S.pop();
            S.push(x2/x1);
        }
        if(op == mult)
        {
            x2 = S.top();
            S.pop();
            S.push(x2*x1);
        }
        if(op == paran)
        {
            total += x1;
            break;
        }
    }
    return total;
}

void Do()
{
    int i,j,x;
    int x1,x2;
    int op;
    int total = 0;
    S.push(stop);
    for(i = 0; i<n; ++i)
    {
        if(isdigit(s[i]))
        {
            x = Number(i);
            S.push(x);
        }
        if(s[i] == '(')
            S.push(paran);
        if(s[i] == '/')
            S.push(div);
        if(s[i] == '*')
            S.push(mult);
        if(s[i] == '+')
            S.push(plus);
        if(s[i] == '-')
            S.push(minus);
        if(s[i] == ')')
           S.push(Eval());
    }/*
    while(!S.empty())
    {
        cout<<S.top()<<" ";
        S.pop();
    }*/
    while(S.top() != stop )
    {
        x1 = S.top();
        S.pop();
        op = S.top();
        S.pop();
        if(op == plus)
            total += x1;
        if(op == minus)
            total -= x1;
        if(op == div)
        {
            x2 = S.top();
            S.pop();
            S.push(x2/x1);
        }
        if(op == mult)
        {
            x2 = S.top();
            S.pop();
            S.push(x2*x1);
        }
        if(op == stop)
        {
            total += x1;
            break;
        }
    }
    fout<<total;
}

int main()
{
    Read();
    Do();
    return 0;
}