Cod sursa(job #850659)

Utilizator andreitulusAndrei andreitulus Data 8 ianuarie 2013 18:56:08
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include<fstream>
using namespace std;

ifstream fin("exp.in");
ofstream fout("exp.out");

struct nod{int nr; int t; char o; nod *st,*dr;};
nod *r;

int p[100005],n;

struct expresie{int tp; int nm; char cr;} e[100005];


void citire()
{char c;
 int pp=0,m;
 
 fin.get(c);
 
 while(c!='\n')
 {
    while(c==' ' && c!='\n')
		fin.get(c);
	
	//if(c=='\n')
		//return ;
	
	 if(c=='(')
		pp+=10,fin.get(c);
	 else
		 if(c==')')
			pp-=10,fin.get(c);
		 else
			 if(c=='-' || c=='+')
			 {
				 n++; e[n].tp=2; e[n].cr=c; p[n]=pp+1; fin.get(c);
			 }
			 else
				 if(c=='*' || c=='/')
				 {
					 n++; e[n].tp=2; e[n].cr=c; p[n]=pp+10; fin.get(c);
				 }
				 else
				 {
					 m=0;
					 n++;
					 e[n].tp=1;
					 
					 while(c>='0' && c<='9' && c!='\n')
					 {
						 m=m*10+c-'0';
						 fin.get(c);
					 }
					 
					 p[n]=pp+1000;
					 e[n].nm=m;
				 }
 }
	
 
fin.close();
}


 

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].tp==1)
  {
    q->nr=e[hh].nm;
    q->t=1;
  }
  else
   {
    q->o=e[hh].cr;
    q->t=2;
   }	
   

 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 evaluare(nod *r)
{
	int a,b;
	
	if(r->t==2)
	{
		a=evaluare(r->st);
		b=evaluare(r->dr);
		
		if(r->o=='+')
			return a+b;
		if(r->o=='-')
			return a-b;
		if(r->o=='/')
			return a/b;
		if(r->o=='*')
			return a*b;
	}
	else
		return r->nr;
}





int main()
{
	citire();
	r=creare(1,n);  
	fout<<evaluare(r);

	fout.close();
	return 0;
}