Pagini recente » Cod sursa (job #2464696) | Cod sursa (job #2931167) | Cod sursa (job #2576026) | Cod sursa (job #98435) | Cod sursa (job #2046908)
#include <fstream>
#include <stack>
#include <string>
#include <map>
using namespace std;
ifstream fi("evaluare.in");
ofstream fo("evaluare.out");
map<char,pair<int,int> > OP;
stack<char> S;
bool oper(char c)
{
return c=='+'||c=='-'||c=='*'||c=='/'||c=='^';
}
bool cifra(char c)
{
return c>='0'&&c<='9';
}
void initOP()
{
OP['+']={1,0},OP['-']={1,0},OP['*']={2,0},OP['/']={2,0},OP['^']={3,1};
}
string rpn(string l)
{
string rez;
initOP();
for(int i=0;i<l.size();i++)
{
char c=l[i];
if(cifra(c))
{
rez+=c;
if(i==l.size()-1||!cifra(l[i+1]))
rez+='|';
}
else if(oper(c))
{
while(!S.empty()&&OP[S.top()].first>=OP[c].first&&OP[S.top()].second==0)
{
rez+=S.top();
S.pop();
}
S.push(c);
}
else if(c=='(')
S.push(c);
else if(c==')')
{
while(S.top()!='(')
{
rez+=S.top();
S.pop();
}
S.pop();
}
}
while(!S.empty())
{
rez+=S.top();
S.pop();
}
return rez;
}
int op(int a,int b,int operatie)
{
if(operatie=='+')
return a+b;
if(operatie=='-')
return a-b;
if(operatie=='*')
return a*b;
if(operatie=='/')
return a/b;
}
int eval(string s)
{
int crt=0;
stack<int> S;
for(auto c:s)
{
if(cifra(c))
crt=crt*10+(c-'0');
else
if(oper(c))
{
int a=S.top();
S.pop();
int b=S.top();
S.pop();
S.push(op(b,a,c));
}
else
{
S.push(crt);
crt=0;
}
}
return S.top();
}
string s;
int main()
{
fi>>s;
s=rpn(s);
fo<<eval(s);
fi.close();
fo.close();
return 0;
}