Cod sursa(job #2215743)

Utilizator Johnny07Savu Ioan-Daniel Johnny07 Data 23 iunie 2018 14:47:38
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.47 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;
char ch[100010];
ifstream f("evaluare.in");
ofstream g("evaluare.out");
stack <int> s;
int poz,a[100010],n,b[100010];

void transforma ()
{
    int i=0;
    n--;
    poz=0;
    while (i<=n)
    {
        if (ch[i]>='0' && ch[i]<='9'){
                poz++;
                while (ch[i]>='0' && ch[i]<='9')
        {
        a[poz]*=10;
        a[poz]+=ch[i]-48;
        i++;
        }
        }
        else
        {
            poz++;
            a[poz]=ch[i];
            a[poz]=-a[poz];
            i++;
        }
    }
}

void postfix()
{
    poz=0;
    for (int i=1;i<=n;i++)
    {
        if (a[i]>=0)
        {
            poz++; b[poz]=a[i];
        }
        else
        {
            if (a[i]==-40) s.push(a[i]);
            if (a[i]==-43 || a[i]==-45)
            {
                while (!s.empty() && s.top()!=-40)
                {
                    poz++;
                    b[poz]=s.top();
                    s.pop();
                }
                s.push(a[i]);
            }
            if (a[i]==-42 || a[i]==-47)
            {
                while (!s.empty() && s.top()!=-40 && s.top()!=-43 && s.top()!=-45)
                {
                    poz++;
                    b[poz]=s.top();
                    s.pop();
                }
                s.push(a[i]);
            }
            if (a[i]==-41){ while (!s.empty() && s.top()!=-40)
                                {
                    poz++;
                    b[poz]=s.top();
                    s.pop();
                }
            s.pop();
            }
        }
    }
    while (!s.empty())
    {
        poz++;
        b[poz]=s.top();
        s.pop();
    }
}

void evaluate()
{
    while (!s.empty ()) s.pop();
    int aux1, aux2,res;
    for (int i=1;i<=poz;i++)
    {
        if (b[i]>=0) s.push(b[i]);
        else
        {
            aux2=s.top();
            s.pop();
            aux1=s.top();
            s.pop();
            char x=-b[i];
            if (x=='+') res=aux1+aux2;
            if (x=='-') res=aux1-aux2;
            if (x=='*') res=aux1*aux2;
            if (x=='/') res=aux1/aux2;
            s.push(res);
        }

    }
    g<<s.top();
}



int main()
{
    f.getline (ch,100010);
    n=strlen(ch);
    transforma();
    n=poz;
    postfix();
    evaluate();


    return 0;
}