Pagini recente » Cod sursa (job #1402112) | Cod sursa (job #1230637) | Cod sursa (job #2710784) | Cod sursa (job #1989842) | Cod sursa (job #1408153)
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
struct elem
{
long long rez,p,nr;
char op1,op2;
bool op;
elem():
rez(0),p(1),nr(0),op1('+'),op2('*'),op(false)
{
}
};
string expr;
stack < elem > st;
long long rez;
void citire()
{
expr.reserve(100008);
getline(in,expr);
in.close();
}
void evaluare()
{
volatile char c2;
volatile long long nr2;
expr += '+';
long long x;
st.push(elem());
//10 + 20 * 30
for(auto c = expr.begin(); c != expr.end(); c++)
{
c2=*c;
if(*c == '+' || *c=='-')
{
if(st.top().op==0)
{
if(st.top().op1=='+')
st.top().rez+=st.top().nr;
else
st.top().rez-=st.top().nr;
}
else
{
if(st.top().op2=='*')
st.top().p*=st.top().nr;
else
st.top().p/=st.top().nr;
if(st.top().op1 == '+')
st.top().rez+=st.top().p;
else
st.top().rez-=st.top().p;
}
st.top().op=0;
st.top().op1=*c;
}
else if(*c == '*' || *c == '/')
{
if(st.top().op==0)
{
st.top().p=st.top().nr;
st.top().op=1;
}
else
{
if(st.top().op2=='*')
st.top().p*=st.top().nr;
else
st.top().p/=st.top().nr;
}
st.top().op2=*c;
}
else if (*c == ')')
{
if(st.top().op==1)
if(st.top().op2=='*')
st.top().p*=st.top().nr;
else
st.top().p/=st.top().nr;
if(st.top().op1=='+')
st.top().rez+=st.top().p;
else
st.top().rez-=st.top().p;
x=st.top().rez;
st.pop();
st.top().nr=x;
}
else if(*c == '(')
st.push(elem());
else
{
st.top().nr=(*c-'0');
c++;
while(*c>='0' && *c<='9')
{
st.top().nr*=10;
st.top().nr+=(*c-'0');
c++;
}
c--;
nr2=st.top().nr;
}
//cout<<st.size()<<' '<<st.top().rez<<' '<<st.top().p<<'\n';
}
rez=st.top().rez;
}
void afisare()
{
out<<rez;
}
int main()
{
citire();
evaluare();
afisare();
return 0;
}