Pagini recente » Cod sursa (job #478047) | Cod sursa (job #2160331) | Cod sursa (job #1681245) | Cod sursa (job #840764) | Cod sursa (job #494579)
Cod sursa(job #494579)
#include <stdio.h>
#include <stack>
#include <stdio.h>
#define LMax 100005
using namespace std;
const char IN[]="evaluare.in",OUT[]="evaluare.out";
char s[LMax],p[LMax];
void strToPol(char *s,char *p)
{
int i,l=0;
stack<char> st;
st.push('\0');
for (i=0;s[i]!='\0';i++)
{
while (s[i]>='0' && s[i]<='9' && s[i])
{
p[l++]=s[i++];
}
if (s[i-1]>='0' && s[i-1]<='9') p[l++]=' ';
if (s[i]=='+' || s[i]=='-')
{
while ( (st.top()!='\0' && st.top()!='(')&& (st.top()=='+' || st.top()=='-'|| st.top()=='*' || st.top()=='/'))
p[l++]=st.top(),st.pop();
st.push(s[i]);
}
if (s[i]=='*' || s[i]=='/')
{
while ( (st.top()!='\0' && st.top()!='(') && ( st.top()=='*' || st.top()=='/' ) )
p[l++]=st.top(),st.pop();
st.push(s[i]);
}
if (s[i]=='(')
st.push(s[i]);
if (s[i]==')')
{
while (st.top()!='(')
p[l++]=st.top(),st.pop();
st.pop();
}
}
while (st.top()!='\0')
p[l++]=st.top(),st.pop();
}
int EvalPol(char *p)
{
int i;
stack<int> st;
for (i=0;p[i]!='\0';i++)
{
if (p[i]>='0' && p[i]<='9')
{
int x=0;
while (p[i]>='0' && p[i]<='9')
x= x*10 + p[i]-'0',i++;
st.push(x);
}
if (p[i]=='+' || p[i]=='-' || p[i]=='*' || p[i]=='/')
{
int x,y;
y=st.top(),st.pop();
x=st.top(),st.pop();
if (p[i]=='+')
st.push(x+y);
if (p[i]=='-')
st.push(x-y);
if (p[i]=='*')
st.push(x*y);
if (p[i]=='/')
st.push(x/y);
}
}
return st.top();
}
int main()
{
freopen(IN,"r",stdin);
fgets(s, LMax , stdin);
fclose(stdout);
s[strlen(s)-1]='\0';
strToPol(s,p);
freopen(OUT,"w",stdout);
printf("%d\n",EvalPol(p));
fclose(stdout);
return 0;
}