Cod sursa(job #1866765)

Utilizator stefanst77Luca Stefan Ioan stefanst77 Data 3 februarie 2017 15:18:53
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.27 kb
#include <bits/stdc++.h>
#define paran   1000000001      /// (
#define scadere 1000000002      /// -
#define inm     1000000003      /// *
#define imp     1000000004      /// /

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

char a[100007];
int st[100007], top;

void Rezolvare()
{
    int i, nr;

    for (i=0; a[i]!=0; )
    {
        if (a[i]=='+')
            i++;

        if (a[i]=='-')
        {
            st[++top]=scadere;
            i++;
        }

        if (a[i]=='*')
        {
            st[++top]=inm;
            i++;
        }

        if (a[i]=='/')
        {
            st[++top]=imp;
            i++;
        }

        if (a[i]=='(')
        {
            st[++top]=paran;
            i++;
        }

        if (a[i]>='0' && a[i]<='9')
        {

            nr=0;
            while (a[i]>='0' && a[i]<='9')
                nr=nr*10+a[i++]-'0';

            if (st[top]==scadere)
            {
                nr*=-1;
                top--;
            }

            while (st[top]==inm && top>0)
            {
                top--;
                nr=st[top]*nr;
                top--;
            }

            while (st[top]==imp && top>0)
            {
                top--;
                nr=st[top]/nr;
                top--;
            }

            st[++top]=nr;
        }

        if (a[i]==')')
        {
            nr=0;

            while (st[top]!=paran && top>0)
            {
                nr+=st[top];
                top--;
            }
            top--;

            while (st[top]==inm && top>0)
            {
                top--;
                nr=st[top]*nr;
                top--;
            }

            while (st[top]==imp && top>0)
            {
                top--;
                nr=st[top]/nr;
                top--;
            }

            if (st[top]==scadere)
            {
                nr*=-1;
                top--;
            }

            st[++top]=nr;
            i++;
        }
    }

    nr=0;
    for (i=1; i<=top; i++)
        nr+=st[i];
    fout << nr << "\n";
}

int main()
{
    fin >> a;
    Rezolvare();
    fin.close();
    fout.close();
    return 0;
}