Cod sursa(job #1365724)

Utilizator radu_cosmaRadu Cosma radu_cosma Data 28 februarie 2015 14:41:41
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.47 kb
#include <fstream>
#include <cstring>
#define parantezadeschisa 1000000001
#define Plus 1000000002
#define ori 1000000003
#define impartit 1000000004
#define Minus 1000000005
#define NMAX 100010
using namespace std;

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

char s[NMAX];
int i,q,l,st[NMAX],top=0;

int main()
{
    in>>(s+1);
    l=strlen(s+1);
    top=0;
    for(i=1; i<=l; i++)
    {
        if(s[i]=='(') st[++top]=parantezadeschisa;
        else if(s[i]=='+') st[++top]=Plus;
        else if(s[i]=='-') st[++top]=Minus;
        else if(s[i]=='*') st[++top]=ori;
        else if(s[i]=='/') st[++top]=impartit;
        else if(s[i]==')')
        {
            st[top-1]=st[top--];
            if(st[top-1]==ori)
            {
                st[top-2]=st[top-2]*st[top];
                --top;
                --top;
            }
            else if(st[top-1]==impartit)
            {
                st[top-2]=st[top-2]/st[top];
                --top;
                --top;
            }
            bool ok=true;
            while(ok)
            {
                ok=false;
                if((st[top-1]==Plus or st[top-1]==Minus) && (s[i+1]=='+' or s[i+1]=='-' or s[i+1]==')' or s[i+1]==0))
                {
                    ok=true;
                    if(st[top-1]==Plus) st[top-2]+=st[top];
                    else st[top-2]-=st[top];
                    top -= 2;
                }
            }
        }
        else
        {
            int nr=0;
            while('0'<=s[i] && s[i]<='9')
            {
                nr=nr*10+s[i]-'0';
                ++i;
            }
            --i;
            st[++top]=nr;
            if(st[top-1]==ori)
            {
                st[top-2]=st[top-2]*st[top];
                --top;
                --top;
            }
            else if(st[top-1]==impartit)
            {
                st[top-2]=st[top-2]/st[top];
                --top;
                --top;
            }
            bool ok=true;
            while(ok)
            {
                ok=false;
                if((st[top-1]==Plus or st[top-1]==Minus) && (s[i+1]=='+' or s[i+1]=='-' or s[i+1]==')' or s[i+1]==0))
                {
                    ok=true;
                    if(st[top-1]==Plus) st[top-2]+=st[top];
                    else st[top-2]-=st[top];
                    top -= 2;
                }
            }
        }
    }
    out<<st[top];
    return 0;
}