Pagini recente » Cod sursa (job #1336785) | Cod sursa (job #2454465) | Cod sursa (job #1062833) | Cod sursa (job #2848343) | Cod sursa (job #2171019)
#include <fstream>
#include <deque>
#include <cstring>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100001];
int lg;
deque <int> val;
deque <char> op;
void Read()
{
fin>>s;
lg=strlen(s);
fin.close();
}
int getNumber(int &cursor)
{
int nr=0;
while(isdigit(s[cursor]))
{
nr*=10;
nr+=s[cursor]-'0';
++cursor;
}
--cursor;
return nr;
}
bool Operator(char x)
{
if(strchr("+-*/",x)) return 1;
else return 0;
}
int Prioritate(char x)
{
if(x=='(') return 0;
if(x=='+' || x=='-') return 1;
if(x=='*' || x=='/') return 2;
}
void Do()
{
int A,B;
int rez;
char operatie;
int prior;
int NR;
for(int i=0; i<lg; ++i)
{
if(isdigit(s[i]))
{
NR=getNumber(i);
val.push_back(NR);
}
if(s[i]=='(') op.push_back(s[i]);
if(s[i]==')')
{
while(op.back()!='(')
{
B=val.back(); val.pop_back();
A=val.back(); val.pop_back();
operatie=op.back(); op.pop_back();
if(operatie=='+') rez=A+B;
if(operatie=='*') rez=A*B;
if(operatie=='/') rez=A/B;
if(operatie=='-') rez=A-B;
val.push_back(rez);
}
op.pop_back();
}
if(Operator(s[i]))
{
prior=Prioritate(s[i]);
while(!op.empty() && op.back()!='(' && Prioritate(op.back())>=prior)
{
B=val.back(); val.pop_back();
A=val.back(); val.pop_back();
operatie=op.back(); op.pop_back();
if(operatie=='+') rez=A+B;
if(operatie=='*') rez=A*B;
if(operatie=='/') rez=A/B;
if(operatie=='-') rez=A-B;
val.push_back(rez);
}
op.push_back(s[i]);
}
}
while(op.size()>0)
{
B=val.back(); val.pop_back();
A=val.back(); val.pop_back();
operatie=op.back(); op.pop_back();
if(operatie=='+') rez=A+B;
if(operatie=='*') rez=A*B;
if(operatie=='/') rez=A/B;
if(operatie=='-') rez=A-B;
val.push_back(rez);
}
fout<<val.back()<<'\n';
}
int main()
{
Read();
Do();
return 0;
}