Pagini recente » Cod sursa (job #2948564) | Cod sursa (job #291270) | Istoria paginii runda/graf2 | Cod sursa (job #1282148) | Cod sursa (job #2039940)
#include <fstream>
#define PARANTEZA -1000000001
#define PLUS -1000000002
#define MINUS -1000000003
#define MUL -1000000004
#define DIV -1000000005
using namespace std;
const int DIM = 100010;
char s[DIM];
int st[DIM];
int vf = 0;
/*
( -1
+ -2
- -3
* -4
/ -5
*/
void Read()
{
ifstream f("evaluare.in");
f.getline(s + 1, DIM);
f.close();
}
int GetStackElement(int &i)
{
if (s[i] == '(')
{
return PARANTEZA;
}
if (s[i] == '+')
{
return PLUS;
}
if (s[i] == '-')
{
return MINUS;
}
if (s[i] == '*')
{
return MUL;
}
if (s[i] == '/')
{
return DIV;
}
if ('0' <= s[i] && s[i] <= '9')
{
int ret = 0;
while ('0' <= s[i] && s[i] <= '9')
{
ret = ret * 10 + s[i] - '0';
++i;
}
--i;
return ret;
}
return 0;
}
bool CheckMulOrDiv()
{
if (st[vf] == PARANTEZA)
return false;
if (vf - 1 >= 1 && (st[vf - 1] == MUL || st[vf - 1] == DIV))
{
int rez = st[vf - 2];
if (st[vf - 1] == MUL)
{
rez = rez * st[vf];
}
else
{
rez = rez / st[vf];
}
vf -= 3;
st[++vf] = rez;
return true;
}
return false;
}
void MakePlusAndMinus()
{
int rez = 0;
while (true)
{
int semn = 1;
if (st[vf - 1] == MINUS)
semn = -1;
if (st[vf - 1] == PLUS)
semn = 1;
rez += semn * st[vf];
--vf;
if (st[vf] == MINUS || st[vf] == PLUS)
--vf;
if (vf == 0 || st[vf] == PARANTEZA)
{
st[++vf] = rez;
return;
}
}
}
void Solve()
{
for (int i = 1; s[i] != 0; ++i)
{
if (s[i] == ')')
{
MakePlusAndMinus(); // (rez
int x = st[vf];
--vf; --vf;
st[++vf] = x;
CheckMulOrDiv();
}
else
{
st[++vf] = GetStackElement(i);
CheckMulOrDiv();
}
}
MakePlusAndMinus();
}
void Write()
{
ofstream g("evaluare.out");
g << st[1] << "\n";
g.close();
}
int main()
{
Read();
Solve();
Write();
return 0;
}