Cod sursa(job #2330775)
Utilizator | Data | 28 ianuarie 2019 20:30:31 | |
---|---|---|---|
Problema | Evaluarea unei expresii | Scor | 90 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 2.85 kb |
#include <bits/stdc++.h>
using namespace std;
char s[100005];
int op1(int nr1,int nr2,char ch)
{
if(ch=='+')return nr1+nr2;
if(ch=='-')return nr1-nr2;
if(ch=='/')return nr1/nr2;
if(ch=='*')return nr1*nr2;
}
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
fgets(s+1,100005,stdin);
int n=strlen(s+1);
s[n]=NULL;
--n;
int i;
stack<int>st;
stack<char>op;
for(i=1;i<=n;i++)
{
if(s[i]==' ')continue;
int nr=0,ar=i;
while(s[ar]>='0'&&s[ar]<='9')
{
nr=nr*10+s[ar]-'0';
ar++;
}
if(ar!=i)
{
st.push(nr);
i=ar-1;
continue;
}
if(s[i]=='(')
{
op.push(s[i]);
continue;
}
if((s[i]=='+')||(s[i]=='-'))
{
if(op.empty())
{
op.push(s[i]);
continue;
}
if(op.top()=='(')
{
op.push(s[i]);
continue;
}
int nr1=st.top();st.pop();
st.top()=op1(st.top(),nr1,op.top());
op.pop();
op.push(s[i]);
}
if((s[i]=='*')||(s[i]=='/'))
{
if(op.empty())
{
op.push(s[i]);
continue;
}
if(((op.top()=='(')||(op.top()=='+'))||(op.top()=='-'))
{
op.push(s[i]);
continue;
}
int nr1=st.top();st.pop();
st.top()=op1(st.top(),nr1,op.top());
op.pop();
op.push(s[i]);}
if(s[i]==')')
{
int cnt=0;
while(!op.empty())
{
if(op.top()=='(')
{
op.pop();
break;
}
int nr1=st.top();
st.pop();
st.top()=op1(st.top(),nr1,op.top());
op.pop();
}
}
}
while(!op.empty())
{
if(op.top()=='(')
{
op.pop();
continue;
}
int nr1=st.top();
st.pop();
st.top()=op1(st.top(),nr1,op.top());
op.pop();
}
printf("%d",st.top());
return 0;
}