Pagini recente » Cod sursa (job #848467) | Cod sursa (job #2851502) | Cod sursa (job #2222248) | Cod sursa (job #1324030) | Cod sursa (job #2339894)
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cctype>
using namespace std;
char op[100005];
int rez[100005];
int pr(char ch)
{
switch(ch)
{
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
default: return 0;
}
}
void eval(int top1,int top2)
{
if(op[top1]=='+')
rez[top2-1]=rez[top2-1]+rez[top2];
if(op[top1]=='-')
rez[top2-1]=rez[top2-1]-rez[top2];
if(op[top1]=='*')
rez[top2-1]=rez[top2-1]*rez[top2];
if(op[top1]=='/')
rez[top2-1]=rez[top2-1]/rez[top2];
}
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
int nr,top1=0,top2=0;
char ch;
scanf("%c",&ch);
while(isdigit(ch) || ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='(' || ch==')')
{
if(isdigit(ch))
{
nr=ch-'0';
scanf("%c",&ch);
while(isdigit(ch))
{
nr=nr*10+(ch-'0');
scanf("%c",&ch);
}
rez[++top2]=nr;
}
else
{
if(top1==0 || ch=='(' || pr(op[top1])<pr(ch))
op[++top1]=ch;
else
{
if(ch==')')
{
while(op[top1]!='(')
{
eval(top1,top2);
top1--;
top2--;
}
top1--;
}
else
{
if(pr(op[top1])>=pr(ch))
{
while(pr(op[top1])>=pr(ch))
{
eval(top1,top2);
top1--;
top2--;
}
op[++top1]=ch;
}
}
}
scanf("%c",&ch);
}
}
while(top1)
{
eval(top1,top2);
top1--;
top2--;
}
printf("%d",rez[1]);
return 0;
}