Pagini recente » Cod sursa (job #3281502) | Cod sursa (job #2901779) | Cod sursa (job #2717470) | Cod sursa (job #2834341) | Cod sursa (job #852566)
Cod sursa(job #852566)
#include<fstream>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.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;
}
}
}
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);
fin.close();
fout.close();
return 0;
}