Pagini recente » Cod sursa (job #1628747) | Cod sursa (job #1132879) | Cod sursa (job #2105486) | Cod sursa (job #2007735) | Cod sursa (job #509757)
Cod sursa(job #509757)
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char s[100003];
unsigned long lg;
struct nod
{
char info[12];
struct nod *st,*dr;
};
typedef nod* Arbore;
Arbore r;
Arbore CreareArbore(int&);
Arbore Termen(int&);
Arbore Factor(int&);
long rezultat(Arbore r)
{
if(r)
{
if(r->st!=r->dr)
switch(r->info[0])
{
case '+': return rezultat(r->st)+rezultat(r->dr);break;
case '-': return rezultat(r->st)-rezultat(r->dr);break;
case '*': return rezultat(r->st)*rezultat(r->dr);break;
case '/': return rezultat(r->st)/rezultat(r->dr);break;
}
else
return atoi(r->info);
}
}
int main()
{
int i=0;
f>>s;
lg=strlen(s)-1;
r=CreareArbore(i);
g<<rezultat(r);
f.close();
g.close();
return 0;
}
Arbore CreareArbore(int &i)
{
Arbore p,r1;
char t[12];
int j=0;
if(i>lg)
return NULL;
r1=Termen(i);
if(i>lg || s[i]==')')
return r1;
p=new nod;
if(!(s[i]>='0' && s[i]<='9'))
{
t[0]=s[i++];
t[1]='\0';
strcpy(p->info,t);
}
else
{
while(s[i]>='0' && s[i]<='9')
{
t[j++]=s[i];
i++;
}
t[j]='\0';
strcpy(p->info,t);
}
p->st=r1;
p->dr=CreareArbore(i);
return p;
}
Arbore Termen(int &i)
{
Arbore p,r1;
char t[12];
int j=0;
r1=Factor(i);
if(i>lg || s[i]!='*')
return r1;
p=new nod;
if(!(s[i]>='0' && s[i]<='9'))
{
t[0]=s[i++];
t[1]='\0';
strcpy(p->info,t);
}
else
{
while(s[i]>='0' && s[i]<='9')
{
t[j++]=s[i];
i++;
}
t[j]='\0';
strcpy(p->info,t);
}
p->st=r1;
p->dr=Termen(i);
return p;
}
Arbore Factor(int &i)
{
Arbore p;
char t[12];
int j=0;
if(s[i]=='(')
{
++i;
p=CreareArbore(i);
i++;
return p;
}
p=new nod;
if(!(s[i]>='0' && s[i]<='9'))
{
t[0]=s[i++];
t[1]='\0';
strcpy(p->info,t);
}
else
{
while(s[i]>='0' && s[i]<='9')
{
t[j++]=s[i];
i++;
}
t[j]='\0';
strcpy(p->info,t);
}
p->st=p->dr=NULL;
return p;
}