Cod sursa(job #1317881)

Utilizator Eman98Ghinea Mihail Emanuel Eman98 Data 15 ianuarie 2015 12:29:32
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include <fstream>
#include <cstring>
using namespace std;
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
int calcul(char ch,int a,int b)
{
    if(ch=='+')
        return a+b;
    if(ch=='-')
        return a-b;
    if(ch=='*')
        return a*b;
    if(ch=='/')
        return a/b;
}
int n,i,ok,nr,od[100001],a,b,vf1,vf;
char s[100001],pr[126],op[100001],ch;
int main()
{
    cin>>s+1;
    n=strlen(s+1);
    pr['+']=pr['-']=1;
    pr['*']=pr['/']=2;
    for(i=1;i<=n;i++)
    {

        if(s[i]>='0'&&s[i]<='9')
        {
            nr=nr*10+(s[i]-'0');
            ok=1;
        }
        else
        {
            if(s[i]=='(')
               {
                   if(ok==1)
                    {
                        vf1++;
                        od[vf1]=nr;
                        ok=0;nr=0;
                    }
                   op[++vf]=s[i];
               }
            else
            {
                if(s[i]==')')
                {
                    if(ok==1)
                    {
                        vf1++;
                        od[vf1]=nr;
                        ok=0;nr=0;
                    }
                    while(op[vf]!='(')
                    {
                        ch=op[vf];vf--;
                        b=od[vf1];vf1--;
                        a=od[vf1];
                        od[vf1]=calcul(ch,a,b);
                    }
                    vf--;
                }
                else
                {
                    if(ok==1)
                    {
                        vf1++;
                        od[vf1]=nr;
                        ok=0;nr=0;
                    }
                    while(vf1>0&&pr[s[i]]<=pr[op[vf]])
                    {
                        ch=op[vf];vf--;
                        b=od[vf1];vf1--;
                        a=od[vf1];
                        od[vf1]=calcul(ch,a,b);
                    }
                    op[++vf]=s[i];
                }
            }
        }
    }

    while(vf>0)
    {
        if(ok==1)
        {
            vf1++;
            od[vf1]=nr;
            ok=0;nr=0;
        }
        ch=op[vf];vf--;
        b=od[vf1];vf1--;
        a=od[vf1];
        od[vf1]=calcul(ch,a,b);
    }
    cout<<od[1];
    return 0;
}