Cod sursa(job #1365713)

Utilizator calinalexandruAlexandru Calin calinalexandru Data 28 februarie 2015 14:38:08
Problema Evaluarea unei expresii Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.42 kb
#include <fstream>
#include <cstring>
#define parantezadeschisa 1e9+1
#define pluss 1e9+2
#define minuss 1e9+3
#define ori 1e9+4
#define impartit 1e9+5
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
char s[100010];
int st[100010];
int main()
{
    int n,i,top=0;
    in>>(s+1);
    n=strlen(s+1);
    for(i=1;i<=n;i++)
    {
        if(s[i]=='(') st[++top]=parantezadeschisa;
        else if(s[i]=='+') st[++top]=pluss;
        else if(s[i]=='-') st[++top]=minuss;
        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-2;
            }
            else if(st[top-1]==impartit)
            {
                st[top-2]=st[top-2]/st[top];
                top=top-2;
            }
            bool ok=true;
            while(ok)
            {
                ok=false;
                if((st[top-1]==pluss || st[top-1]==minuss) && (s[i+1]=='+' || s[i+1]=='-' || s[i+1]==')' || s[i+1]==0))
                {
                    ok=true;
                    if(st[top-1]==pluss) st[top-2]=st[top-2]+st[top];
                    else st[top-2]=st[top-2]+st[top];
                    top=top-2;
                }
            }
        }
        else
        {
            int nr=0;
            while(s[i]<='9' && s[i]>='0')
            {
                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-2;
            }
            else if(st[top-1]==impartit)
            {
                st[top-2]=st[top-2]/st[top];
                top=top-2;
            }
            bool ok=true;
            while(ok)
            {
                ok=false;
                if((st[top-1]==pluss || st[top-1]==minuss) && (s[i+1]=='+' || s[i+1]=='-' || s[i+1]==')' || s[i+1]==0))
                {
                    ok=true;
                    if(st[top-1]==pluss) st[top-2]=st[top-2]+st[top];
                    else st[top-2]=st[top-2]+st[top];
                    top=top-2;
                }
            }
        }
    }
    out<<st[top];
    in.close();
    out.close();
    return 0;

}