Cod sursa(job #1891776)
Utilizator | Data | 24 februarie 2017 12:18:26 | |
---|---|---|---|
Problema | Evaluarea unei expresii | Scor | 20 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 3.92 kb |
#include<cstdio>
#include<stack>
#include<cctype>
#include<cstring>
using namespace std;
const int NMAX=100005;
stack <int> st;
char s[NMAX];
char semn[NMAX];
int main(){
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
int n,ind,q=0;
gets(s);
n=strlen(s);
ind=0;
st.push(0);
while(ind<n){
if(s[ind]=='('){
st.push(0);
ind++;
int nr=0;
while(ind<n && isdigit(s[ind])){
nr=nr*10+(s[ind]-'0');
ind++;
}
st.top()+=nr;
continue;
}
if(s[ind]==')'){
int x=st.top();
st.pop();
int y;
if(!st.empty()){
y=st.top();
if(q){
if(semn[q]=='+')
st.top()=y+x;
else
if(semn[q]=='-')
st.top()=y-x;
else
if(semn[q]=='*')
st.top()=y*x;
else
st.top()=y/x;
q--;
}
else
st.top()=y+x;
ind++;
continue;
}
else{
if(q){
if(semn[q]=='+')
st.push(y+x);
else
if(semn[q]=='-')
st.push(y-x);
else
if(semn[q]=='*')
st.push(y*x);
else
st.push(y/x);
q--;
}
else
st.push(y+x);
ind++;
continue;
}
}
if(s[ind]=='+' || s[ind]=='-'){
char ch1=s[ind];
ind++;
if(s[ind]=='(')
semn[++q]=ch1;
else{
int nr=0;
while(ind<n && isdigit(s[ind])){
nr=nr*10+(s[ind]-'0');
ind++;
}
if(s[ind]=='*' || s[ind]=='/'){
while(ind<n && (s[ind]=='*' || s[ind]=='/')){
ind++;
int nr1=0;
char ch=s[ind-1];
while(ind<n && isdigit(s[ind])){
nr1=nr1*10+s[ind]-'0';
ind++;
}
if(ch=='*')
nr*=nr1;
else
nr/=nr1;
}
int y=st.top();
if(ch1=='+')
st.top()=y+nr;
else
st.top()=y-nr;
}
else{
int y=st.top();
if(ch1=='+')
st.top()=nr+y;
else
st.top()=y-nr;
}
}
}
else{
if(s[ind]=='*' || s[ind]=='/'){
int nr=st.top();
while(ind<n && (s[ind]=='*' || s[ind]=='/')){
ind++;
int nr1=0;
char ch=s[ind-1];
while(ind<n && isdigit(s[ind])){
nr1=nr1*10+s[ind]-'0';
ind++;
}
if(ch=='*')
nr*=nr1;
else
nr/=nr1;
}
st.top()=nr;
}
}
}
printf("%d", st.top());
return 0;
}