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