Pagini recente » Cod sursa (job #964867) | Cod sursa (job #857018) | Cod sursa (job #2537629) | Cod sursa (job #1546663) | Cod sursa (job #3182274)
#include<fstream>
#include<string>
#include<stack>
std::ifstream fin("evaluare.in");
std::ofstream fout("evaluare.out");
std::stack<char>operators;
std::stack<int>nrs;
std::string exp;
long long size;
int eval(int a, int b, char s)
{
if(s=='+')
return a+b;
if(s=='-')
return a-b;
if(s=='*')
return a*b;
return a/b;
}
bool isGood(char op, char current)
{
if((current=='+' || current=='-') && (op=='*' || op=='/'))
return false;
return true;
}
bool isOp(char local)
{
return (local=='-' || local=='+' || local=='*' || local=='/' || local=='(' || local==')');
}
int createNum(int &index)
{
int ans=0;
while(!isOp(exp[index]) && index<size)
{
ans=ans*10;
ans+=exp[index]-'0';
++index;
}
return ans;
}
void solve()
{
for(int index=0; index<size; ++index)
{
if(exp[index]=='(')
operators.push(exp[index]);
else if(exp[index]==')')
{
while(operators.top()!='(')
{
int v1=nrs.top();
nrs.pop();
int v2=nrs.top();
nrs.pop();
char sign=operators.top();
operators.pop();
nrs.push(eval(v2, v1, sign));
}
operators.pop();
}
else if(isOp(exp[index]))
{
if(operators.empty() || isGood(operators.top(), exp[index]))
operators.push(exp[index]);
else
{
do
{
int a=nrs.top();
nrs.pop();
int b=nrs.top();
nrs.pop();
char sign=operators.top();
operators.pop();
nrs.push(eval(b, a, sign));
}while(!operators.empty() && isGood(operators.top(), exp[index]));
operators.push(exp[index]);
}
}
else
{
nrs.push(createNum(index));
--index;
}
}
while(!operators.empty())
{
int a=nrs.top();
nrs.pop();
int b=nrs.top();
nrs.pop();
char sign=operators.top();
operators.pop();
nrs.push(eval(b, a, sign));
}
fout<<nrs.top();
}
int main()
{
fin>>exp;
size=exp.size();
solve();
return 0;
}