Pagini recente » Cod sursa (job #2693183) | Cod sursa (job #2849879) | Cod sursa (job #20302) | Cod sursa (job #296800) | Cod sursa (job #1465445)
#include<cstdio>
#include<stack>
#include<cstring>
using namespace std;
char s[100010];
int fp[100010];
stack<char> stiva;
stack<int> eval;
int f(char c){
if(c=='(')
return -1;
if(c==')')
return -2;
if(c=='+')
return -3;
if(c=='-')
return -4;
if(c=='*')
return -5;
return -6;
}
char transf(int x){
if(x==-3)
return '+';
if(x==-4)
return '-';
if(x==-5)
return '*';
return '/';
}
int main (){
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
int n,k=0,nr,kfp=0,aux;
gets(s);
n=strlen(s);
stiva.push('(');
while(k<n){
if(s[k]>='0'&&s[k]<='9'){
nr=0;
while(s[k]>='0'&&s[k]<='9'){
nr=nr*10+s[k]-'0';
k++;
}
k--;
kfp++;
fp[kfp]=nr;
}
if(s[k]=='(')
stiva.push('(');
if(s[k]==')'){
while(stiva.top()=='+'||stiva.top()=='-'||stiva.top()=='*'||stiva.top()=='/'){
kfp++;
fp[kfp]=f(stiva.top());
stiva.pop();
}
stiva.pop();
}
if(s[k]=='+'||s[k]=='-'){
while(stiva.top()=='+'||stiva.top()=='-'||stiva.top()=='*'||stiva.top()=='/'){
kfp++;
fp[kfp]=f(stiva.top());
stiva.pop();
}
stiva.push(s[k]);
}
if(s[k]=='*'||s[k]=='/'){
while(stiva.top()=='*'||stiva.top()=='/'){
kfp++;
fp[kfp]=f(stiva.top());
stiva.pop();
}
stiva.push(s[k]);
}
k++;
}
while(stiva.top()!='('){
kfp++;
fp[kfp]=f(stiva.top());
stiva.pop();
}
for(k=1;k<=kfp;k++)
if(fp[k]>=0)
eval.push(fp[k]);
else{
nr=eval.top();
eval.pop();
if(fp[k]==-3)
aux=nr+eval.top();
if(fp[k]==-4)
aux=eval.top()-nr;
if(fp[k]==-5)
aux=nr*eval.top();
if(fp[k]==-6)
aux=eval.top()/nr;
eval.pop();
eval.push(aux);
}
printf("%d",eval.top());
return 0;
}