Pagini recente » Cod sursa (job #789725) | Cod sursa (job #2501925) | Cod sursa (job #2808972) | Cod sursa (job #63359) | Cod sursa (job #2276467)
#include <stdio.h>
#include <ctype.h>
#define NIL -1
#define MAX 100000
FILE *fin,*fout;
char ch;
struct arbore{
int cheie,st,dr;
}v[MAX];
int n;
void postord(int nod){
if(v[nod].st!=NIL)
postord(v[nod].st);
if(v[nod].dr!=NIL)
postord(v[nod].dr);
if(v[nod].st==NIL && v[nod].dr==NIL)
fprintf(fout,"%d",v[nod].cheie);
else
fputc(v[nod].cheie,fout);
fprintf(fout," ");
}
int newNode(int cheie, int st, int dr){
v[n].cheie=cheie;
v[n].st=st;
v[n++].dr=dr;
return n-1;
}
int e();
int num(){
int r=0;
while(isdigit(ch)){
r=r*10+ch-'0';
ch=fgetc(fin);
}
return r;
}
int f(){
int nod;
ch=fgetc(fin);
if(ch=='('){
nod=e();
ch=fgetc(fin);
}else
nod=newNode(num(),NIL,NIL);
return nod;
}
int t(){
int st=f();
int nod=st;
while(ch=='*' || ch=='/'){
int aux=ch;
int dr=f();
nod=newNode(aux,st,dr);
st=nod;
}
return nod;
}
int e(){
int st=t();
int nod=st;
while(ch=='+' || ch=='-'){
int aux=ch;
int dr=t();
nod=newNode(aux,st,dr);
st=nod;
}
return nod;
}
int eval(int nod){
if(v[nod].st==NIL && v[nod].dr==NIL)
return v[nod].cheie;
switch(v[nod].cheie){
case '+': return eval(v[nod].st)+eval(v[nod].dr);
case '-': return eval(v[nod].st)-eval(v[nod].dr);
case '*': return eval(v[nod].st)*eval(v[nod].dr);
case '/': return eval(v[nod].st)/eval(v[nod].dr);
}
}
int main(){
fin=fopen("evaluare.in","r");
fout=fopen("evaluare.out","w");
for(int i=0; i<MAX; i++)
v[i].st=v[i].dr=NIL;
int radacina=e();
fprintf(fout,"%d\n",eval(radacina));
fclose(fin);
fclose(fout);
return 0;
}