Cod sursa(job #1317914)
Utilizator | Data | 15 ianuarie 2015 13:12:40 | |
---|---|---|---|
Problema | Evaluarea unei expresii | Scor | 100 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 2.36 kb |
#include <fstream>
#include <string.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100001],op[100001],ch,pr[256];
int od[100001],vf1,vf,i,n,ok,nr,a,b;
int calcul(char ch, int a,int b)
{
if(ch=='+')
return a+b;
if(ch=='*')
return a*b;
if(ch=='/')
return a/b;
if(ch=='-')
return a-b;
}
int main()
{
pr['+']=pr['-']=1;
pr['*']=pr['/']=2;
pr['(']=0;
fin>>s+1;
n=strlen(s+1);
for(i=1;i<=n;i++)
{
if(s[i]>='0'&&s[i]<='9')
{
ok=1;
nr=nr*10+(s[i]-'0');
}
else
if(s[i]=='('){
if(ok==1)
{
vf1++;
od[vf1]=nr;
ok=0;nr=0;
}
op[++vf]=s[i];
}
else
if(s[i]==')')
{
if(ok==1)
{
vf1++;
od[vf1]=nr;
ok=0; nr=0;
}
while(op[vf]!='(')
{
ch=op[vf--];
b=od[vf1--];
a=od[vf1];
od[vf1]=calcul(ch,a,b);
}
vf--;// eliminam (
}
else
{
if(ok==1)
{
vf1++;
od[vf1]=nr;
ok=0;
nr=0;
}
while(vf>0&&pr[op[vf]]>=pr[s[i]])
{
ch=op[vf--];
b=od[vf1--];
a=od[vf1];
od[vf1]=calcul(ch,a,b);
}
op[++vf]=s[i];
}
}
if(ok==1)
{
vf1++;
od[vf1]=nr;
ok=0;
nr=0;
}
while(vf>0)
{
ch=op[vf--];
b=od[vf1--];
a=od[vf1];
od[vf1]=calcul(ch,a,b);
}
fout<<od[1];
return 0;
}