Pagini recente » Cod sursa (job #2164987) | Cod sursa (job #1470828) | Cod sursa (job #2941534) | Cod sursa (job #2941530) | Cod sursa (job #3349681)
#include <iostream>
#include <queue>
#include <fstream>
#include <cstring>
#include <stack>
#define N_MAX 100005
#define MOD 666013
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
string polish;
queue<int> nb;
stack<int> s;
int get_ord(char c) {
if (c == '(')return 0;
if (c == '+' || c == '-')return 1;
return 2;
}
int perform_op(int a, int b, char op) {
if (op == '+')return a + b;
if (op == '-')return a - b;
if (op == '*')return a * b;
return a / b;
}
void clean_paranthesis() {
while (s.top() != '(') {
polish.push_back(s.top());
s.pop();
}
s.pop();
}
void process_operator(char op) {
while (!s.empty() && get_ord(s.top()) >= get_ord(op)) {
char c = s.top();
polish.push_back(c);
s.pop();
}
s.push(op);
}
void infix_to_polish() {
char c;
int nr = 0;
int nr_formation = 0;
while (in >> c) {
if (isdigit(c)) {
nr = nr * 10 + (c - '0');
nr_formation = 1;
}
else {
if (nr_formation) {
polish.push_back('1');
nb.push(nr);
nr = 0;
nr_formation = 0;
}
switch (c)
{
case '(':
s.push(c);
break;
case ')':
clean_paranthesis();
break;
default:
process_operator(c);
}
}
}
if (nr > 0) {
polish.push_back('1');
nb.push(nr);
}
while (!s.empty()) {
polish.push_back(s.top());
s.pop();
}
}
int main()
{
infix_to_polish();
stack<int> st;
for (char c : polish) {
if (c == '1') {
st.push(nb.front());
nb.pop();
}
else {
int nr2 = st.top();
st.pop();
int nr1 = st.top();
st.pop();
st.push(perform_op(nr1, nr2, c));
}
}
out << st.top();
return 0;
}