Pagini recente » Cod sursa (job #2751258) | Cod sursa (job #1173863) | Cod sursa (job #1363987) | Cod sursa (job #504490) | Cod sursa (job #248544)
Cod sursa(job #248544)
#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <stdlib.h>
ifstream fin("expresie.in");
ofstream fout("expresie.out");
char const op1[]="+-", op2[]="*/", op[]="+/-*()", tot[]="0123456789+-/*()";
struct nod{int info; nod *s,*d;};
char e[10000],ch, *c;
long q[10000],p[10000],v;
int n;
nod *rad;
void vsd(nod *i)
{if (i)
{if (e[i->info])
fout<<e[i->info];
else
fout<<q[i->info];
vsd(i->s);
vsd(i->d);
}
}
int calc(nod *i)
{int as,ad;
if (!i->s) return (q[i->info]);
as=calc(i->s);
ad=calc(i->d);
if (e[i->info]=='+') return as+ad;
if (e[i->info]=='-') return as-ad;
if (e[i->info]=='*') return as*ad;
return as/ad;
}
nod *polon(int li, int ls)
{int i,k;
nod *d;
long min=30000;
d=new nod;
for (i=li;i<=ls;i++)
if (p[i]<min)
{min=p[i]; k=i;}
d->info=k;
if (li==ls) {d->s=0; d->d=0;}
else {d->s=polon(li,k-1);
d->d=polon(k+1,ls);}
return d;
}
int main()
{int i,m,sw;
//fin.get(g,900,'\n');
//n=strlen(g)-1;
n=-1;
v=0;
sw=1;
fin.get(ch);;
while (sw)
if (strchr(op1,ch)) //operator de prioritate mica
{n++;
e[n]=ch;
p[n]=v+1;
fin.get(ch);;
if(!strchr(tot,ch)) sw=0;
}
else
if (strchr(op2,ch)) //operator de prioritate mare
{n++;
e[n]=ch;
p[n]=v+10;
fin.get(ch);;
if(!strchr(tot,ch)) sw=0;
}
else
if (ch=='(') //p. deschisa -> crestem v
{v+=10; fin.get(ch);;
if(!strchr(tot,ch)) sw=0;}
else
if (ch==')') //p. inchisa -> descrestem v
{v-=10; fin.get(ch);;
if(!strchr(tot,ch)) sw=0;}
else //NUMAR
{n++;
while (!strchr(op,ch) && sw)
{c=&ch;
q[n]=q[n]*10+atoi(c);
fin.get(ch);;
if(!strchr(tot,ch)) sw=0;
}
p[n]=v+1000;
}
/* for (i=0;i<=n;i++)
{if (g[i]=='(') v+=10;
else
if (g[i]==')') v-=10;
else
{q[i]=v;
if (strchr(op1,g[i])) q[i]+=1;
else
if (strchr(op2,g[i])) q[i]+=10;
else q[i]+=1000;
}
}
m=-1;
for (i=0;i<=n+1;i++)
if (g[i]!='(' && g[i]!=')')
{m++;
e[m]=g[i];
p[m]=q[i];
}
n=m-1;
m=0;
while (fin.get(ch);)
fin>>q[ch-'a'];*/
rad=polon(0,n);
fout<<calc(rad);
fout.close();
return 0;
}