Cod sursa(job #1876684)

Utilizator tiberiu225Iancu Tiberiu tiberiu225 Data 12 februarie 2017 15:42:21
Problema Evaluarea unei expresii Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.64 kb
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
#include <cctype>
using namespace std;

int Convert(char s[], int &i)
{
    int n = strlen(s);
    int ans = 0;
    for(i; i < n; ++i)
    {
        if(isdigit(s[i]))
            ans *= 10, ans += s[i] - '0';
        else break;
    }
    return ans;
}

int Operation(int x, int y, char c)
{
    switch (c)
    {
        case '+' : return x + y;
        case '-' : return y - x;
        case '*' : return x * y;
        case '/' : return y / x;
    };
}

bool Verif(char a, char b) /// return 1 daca trebuie scos din stiva elem din op.top()
{
    switch (a)
    {
        case '+' : {
            return 1;
        }

        case '-' : {
            return 1;
        }

        case '*' : {
            switch (b)
            {
                case '/' : return 1;
                default : return 0;
            };
        }

        case '/' : {
            switch (b)
            {
                case '*' : return 1;
                default : return 0;
            };
        }
    };
}

stack <char> op;
stack <int> pol;
char s[100005];

int main()
{
    freopen("evaluare.in","r",stdin);
    freopen("evaluare.out","w",stdout);

    gets(s);
    int n = strlen(s);

    for(int i = 0; i < n; ++i)
    {
        if(isdigit(s[i]))
        {
            pol.push(Convert(s, i));
            i--;
        }
        else
        {
            if(op.empty() || op.top() == '('){
                op.push(s[i]);
                continue;
            }

            if(s[i] == ')'){
                while(!op.empty() && op.top() != '('){
                    int x = pol.top();
                    pol.pop();
                    int y = pol.top();
                    pol.pop();
                    char c = op.top();
                    op.pop();

                    pol.push(Operation(x, y, c));
                }

                op.pop();
                continue;
            }

            while(!op.empty() && Verif(s[i], op.top()))
            {
                char c = op.top();
                op.pop();
                int x = pol.top();
                pol.pop();
                int y = pol.top();
                pol.pop();

                pol.push(Operation(x, y, c));
            }

            op.push(s[i]);
        }
    }

    while(!op.empty())
    {
        int x = pol.top();
        pol.pop();
        int y = pol.top();
        pol.pop();
        char c = op.top();
        op.pop();

        pol.push(Operation(x, y, c));
    }

    cout << pol.top();
    return 0;
}