Pagini recente » Cod sursa (job #2132127) | Cod sursa (job #223272) | Monitorul de evaluare | Istoria paginii runda/tema_4/clasament | Cod sursa (job #1010811)
#include <iostream>
#include <fstream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <utility>
#include <string>
#include <vector>
using namespace std;
ifstream f("evaluare.in");
string ops("+-*/");
int precs[] = { 10, 10, 20, 20 };
stack<int> output;
stack<char> operators;
int result(int op1, int op2, char op) {
switch (op) {
case '+': return op1 + op2;
case '-': return op2 - op1;
case '*': return op1 * op2;
case '/': return op2 / op1;
}
return 0;
}
void update_output(char op) {
int op1 = output.top();
output.pop();
int op2 = output.top();
output.pop();
output.push(result(op1, op2, op));
}
int prec(char op) {
int pos = ops.find(op);
if (pos == (int)string::npos)
return -1;
return precs[pos];
}
int main() {
string expr;
f >> expr;
bool have_num = false;
int num = 0;
for (int i = 0; i < expr.size(); i++) {
char c = expr[i];
if (isdigit(c)) {
have_num = true;
num = num * 10 + (c - '0');
} else {
if (have_num) {
output.push(num);
num = 0;
have_num = false;
}
if (c == '(') {
operators.push(c);
continue;
}
if (c == ')') {
while (!operators.empty() && operators.top() != '(') {
update_output(operators.top());
operators.pop();
}
if (!operators.empty() && operators.top() == '(')
operators.pop();
continue;
}
if (ops.find(c) != string::npos) {
int p = prec(c);
while (!operators.empty() && prec(operators.top()) >= p) {
update_output(operators.top());
operators.pop();
}
operators.push(c);
}
}
}
if (have_num)
output.push(num);
while (!operators.empty()) {
update_output(operators.top());
operators.pop();
}
fprintf(fopen("evaluare.out", "w"), "%d\n", output.top());
return 0;
}