Cod sursa(job #850669)

Utilizator andrettiAndretti Naiden andretti Data 8 ianuarie 2013 19:10:02
Problema Evaluarea unei expresii Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.41 kb
#include<fstream>
using namespace std;
 
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
 
struct nod
{
    int type;
    char op;
    int nr;
    nod *st,*dr;
};
nod *r,*ps,*us;
 
struct stiva
{
    int t;
    char ch;
    int num;
};
 
 
stiva e[100005];
 
int n,p[100005];
 
 
void cit()
{
    char c;
    int add=0,sum;
     
     
    fin.get(c);
    while(c!='\n')
    {
        while(c==' ' && c!='\n') fin.get(c);
         
        if(c=='\n') return;
         
        if(c=='(') add+=10,fin.get(c);
        else
            if(c==')') add-=10,fin.get(c);
            else
             if(c=='+' || c=='-') { n++; e[n].t=1; e[n].ch=c; p[n]=1+add; fin.get(c); }
                else
                    if(c=='*' || c=='/') { n++; e[n].t=1; e[n].ch=c; p[n]=10+add; fin.get(c); }
                    else
                    {
                        n++;
                        e[n].t=2;
                         
                        sum=0;
                        while(c>='0' && c<='9' && c!='\n')
                        {
                            sum=sum*10+c-'0';
                            fin.get(c);
                        }
                         
                        e[n].num=sum;
                        p[n]=1000+add;
                         
                         
                    }
    }
}
 
nod *creare(int i,int j)
{
    nod *q;
    int hh,h,min;
     
    q=new nod;
    min=999999999;
    for(h=i;h<=j;h++)
        if(min>=p[h])
        {
            min=p[h];
            hh=h;
        }
         
     if(e[hh].t==1)
     {
        q->type=1;
        q->op=e[hh].ch;
     }
     else
     {
        q->type=2;
        q->nr=e[hh].num;
     }
         
      
    if(i==j)
    {
        q->st=0;
        q->dr=0;
    }
    else
    {
        q->st=creare(i,hh-1);
        q->dr=creare(hh+1,j);
    }
     
    return q;
}
 
int eval(nod *q)
{
    int x,y,aux;
     
    if(q->type==1)
    {
        x=eval(q->st);
        y=eval(q->dr);
         
        if(q->op=='+') return x+y;
        if(q->op=='-') return x-y;
        if(q->op=='*') return x*y;
        if(q->op=='/') return x/y;
         
    }
    else
        return q->nr;
     
}   
 
 
int main()
{
    cit();
    r=creare(1,n);
    fout<<eval(r);
  
    fin.close();
    fout.close();
    return 0;
}