Pagini recente » Cod sursa (job #2408405) | Cod sursa (job #2461651) | Cod sursa (job #950763) | Cod sursa (job #119583) | Cod sursa (job #2846191)
#include <iostream>
#include <fstream>
#include <cctype>
#include <stack>
#include <queue>
#include <cstring>
using namespace std;
stack<char> q;
stack<int> st;
char rez[300005];
bool hashigherprecedence(char x, char y)
{
if (x == '*' or x == '/')
return true;
else if (x == '+' or x == '-' or x == '(')
{
if (y == '+' or y == '-' or y == '(')
return true;
else return false;
}
}
bool isopeningpar(char x)
{
if (x == '(')
return true;
else return false;
}
int operatie(char a, int x, int y)
{
if (a == '+')
return x + y;
else if (a == '-')
return x - y;
else if (a == '*')
return x * y;
else if (a == '/')
return x / y;
}
int main()
{
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char c[100005];
int cnt = -1, rezfinal = 0;
fin >> c;
for (int i = 0; i < strlen(c); i++)
{
if (c[i] >= '0' and c[i] <= '9')
rez[++cnt] = c[i];
else if (c[i] == '+' or c[i] == '-' or c[i] == '*' or c[i] == '/')
{
rez[++cnt] = ',';
while (!q.empty() and isopeningpar(q.top()) == false and hashigherprecedence(q.top(), c[i]) == true)
{
rez[++cnt] = q.top();
q.pop();
}
q.push(c[i]);
}
else if (c[i] == '(')
q.push(c[i]);
else if (c[i] == ')')
{
while (!q.empty() and isopeningpar(q.top()) == false)
{
rez[++cnt] = q.top();
q.pop();
}
q.pop();
}
}
while (!q.empty())
{
rez[++cnt] = q.top();
q.pop();
}
for (int i = 0; i < strlen(rez); i++)
{
if (isdigit(rez[i]))
{
int operand = 0;
while(i < strlen(rez) and isdigit(rez[i]))
{
operand = operand * 10 + (rez[i] - '0');
i++;
}
i--;
st.push(operand);
}
else if (rez[i] == '+' or rez[i] == '-' or rez[i] == '*' or rez[i] == '/')
{
int op2 = st.top();
st.pop();
int op1 = st.top();
st.pop();
rezfinal = operatie(rez[i], op1, op2);
st.push(rezfinal);
}
}
fout << st.top();
return 0;
}