Cod sursa(job #2507032)

Utilizator SochuDarabaneanu Liviu Eugen Sochu Data 9 decembrie 2019 14:53:53
Problema Evaluarea unei expresii Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <bits/stdc++.h>

using namespace std;

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

char a[100005];
stack < int > values;
stack < char > ops;

int Operation(int a , int b , char op)
{
    if(op == '-')
        return a - b;

    if(op == '+')
        return a + b;

    if(op == '/')
        return a / b;

    if(op == '*')
        return a * b;
}

short Level(char op)
{
    if(op == '+' || op == '-')
        return 1;

    if(op == '*' || op == '/')
        return 2;

    return 0;
}

int main()
{
    int i , value1 , value2;

    f >> a;

    int n = strlen(a), x = 0;

    for(i = 0 ; i < n ; i++)
    {
        if(a[i] == '(')
            ops.push(a[i]);
        else if(isdigit(a[i]))
        {
            x = 0;

            while(isdigit(a[i]))
                x = x * 10 + a[i] - '0', i++;

            i--;
            values.push(x);
        }
        else if(a[i] == ')')
        {
            while(ops.top() != '(')
            {
                value1 = values.top();
                values.pop();

                value2 = values.top();
                values.pop();

                values.push(Operation(value1 , value2 , ops.top()));
                ops.pop();
            }

            ops.pop(); /// '('
        }
        else
        {
            while(!ops.empty() && Level(ops.top()) >= Level(a[i]))
            {
                value1 = values.top();
                values.pop();

                value2 = values.top();
                values.pop();

                values.push(Operation(value1 , value2 , ops.top()));
                ops.pop();
            }

            ops.push(a[i]);
        }
    }

    while(!ops.empty() && Level(ops.top()) >= Level(a[i]))
    {
        value1 = values.top();
        values.pop();

        value2 = values.top();
        values.pop();

        values.push(Operation(value2 , value1 , ops.top()));
        ops.pop();
    }

    g << values.top();

    return 0;
}