Pagini recente » Cod sursa (job #2451393) | Cod sursa (job #2046034) | Cod sursa (job #1092654) | Cod sursa (job #1707220) | Cod sursa (job #2263915)
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <cstring>
using namespace std;
char op[100005],s[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;
}
}
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
int i,top1=0,top2=0,nr;
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)
op[++top1]=ch;
else
{
if(ch=='(')
op[++top1]=ch;
else
{
if(pr(op[top1])<pr(ch))
op[++top1]=ch;
else
{
if(ch==')')
{
while(op[top1]!='(')
{
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];
top2--;
top1--;
}
top1--;
}
else
{
if(top1 && pr(op[top1])>=pr(ch))
{
while(pr(op[top1])>=pr(ch) && top1)
{
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];
top2--;
top1--;
}
op[++top1]=ch;
}
}
}
}
}
scanf("%c",&ch);
}
}
while(top1)
{
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];
top2--;
top1--;
}
printf("%d",rez[1]);
return 0;
}