Pagini recente » Cod sursa (job #99690) | Cod sursa (job #2839500) | Cod sursa (job #2436757) | Cod sursa (job #1917616) | Cod sursa (job #2869218)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
const int MAX=1e5+5;
int n;
char exp[MAX];
int eval(int st, int dr)
{
int i=st,j,k=0,stk[MAX],nr,nrp,rez=0,aux;
char op[MAX];
op[0]=0;
while(i<=dr)
{
if(exp[i]=='-')
{
stk[++k]=0;
op[k]='-';
i++;
}
else if(exp[i]=='(')
{
j=i,nrp=1;
while(nrp)
{
j++;
if(exp[j]=='(')
nrp++;
else if(exp[j]==')')
nrp--;
}
stk[++k]=eval(i+1,(j++)-1);
if(strchr("+-*/",exp[j]))
op[k]=exp[j];
i=j+1;
}
else if(isdigit(exp[i]))
{
nr=0;
while(isdigit(exp[i]))
nr=nr*10+exp[i++]-'0';
stk[++k]=nr;
if(i<=dr)
op[k]=exp[i++];
}
}
while(k)
{
if(op[k-1]=='+' || op[k-1]==0)
rez+=stk[k--];
else if(op[k-1]=='-')
rez-=stk[k--];
else
{
int kk=k-1;
while(kk && strchr("*/",op[kk]))
kk--;
kk++;
j=kk;
aux=stk[j];
while(j<k)
{
if(op[j]=='*')
aux*=stk[j+1];
else
aux/=stk[j+1];
j++;
}
k=kk;
stk[k]=aux;
}
}
return rez;
}
int main()
{
fin >> exp;
fout << eval(0,strlen(exp)-1);
return 0;
}