Pagini recente » Cod sursa (job #1083908) | Cod sursa (job #1313662) | Cod sursa (job #901404) | Cod sursa (job #662342) | Cod sursa (job #1816626)
#include <fstream>
#include <cstring>
#define nmax 100010
using namespace std;
char s[nmax],st[nmax];
int prioritate(char op)
{
if (op==')') return 1;
if (op=='(') return 2;
if (op=='+' || op=='-') return 3;
if (op=='*' || op=='/') return 4;
return 5;
}
struct coada
{
char op;int x;
}q[nmax];
int xb;
int stiva[nmax];
int eval (int a, int b, char op)
{
if (op=='+') return a+b;
if (op=='-') return a-b;
if (op=='/') return a/b;
if (op=='*') return a*b;
}
int main()
{
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int i,inc=-1,p=-1,n;
fin.get(s,nmax);n=strlen(s);
for (i=0;i<n;)
{
if ( '0'<=s[i] && s[i]<='9' )
{
q[++inc].x=0;
while ( '0'<=s[i] && s[i]<='9' )
{
q[inc].x=10*q[inc].x+s[i]-'0';
i++;
}
}
else
{
if ( strchr("+-*/",s[i]) && s[i] )
{
while ( p>=0 && prioritate(st[p]) >= prioritate(s[i]) )
q[++inc].op=st[p],st[p]=0,p--;
st[++p]=s[i];
}
if (s[i]=='(') st[++p]='(';
if (s[i]==')')
{
while ( st[p]!='(' )
q[++inc].op=st[p],st[p]=0,p--;
st[p]=0,p--;
}
i++;
}
}
while (p>=0)
q[++inc].op=st[p],st[p]=0,p--;
//q = forma poloneza postfixata a expresiei infixate din s
for (i=0;i<=inc;i++,xb=i)
{
if (int(q[i].op)==0)
stiva[++p]=q[i].x;
else
{
stiva[p-1]=eval(stiva[p-1],stiva[p],q[i].op);
stiva[p--]=0;
}
}
fout<<stiva[0]<<'\n';
fin.close();
fout.close();
return 0;
}