Pagini recente » Cod sursa (job #701780) | Cod sursa (job #1081237) | Cod sursa (job #2344144) | Cod sursa (job #1067672) | Cod sursa (job #2863478)
#include <iostream>
#include <fstream>
#include <deque>
#include <stack>
#define NOT_SET 1000000005
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string exp, postfix = "";
int priority(char c) {
if (c == '+' || c == '-') {
return 1;
}
if (c == '*' || c == '/') {
return 2;
}
}
void createPostFixExpression() {
stack<char> op;
string num = "";
for (int i = 0; i < exp.length(); ++i) {
if (exp[i] >= '0' && exp[i] <= '9') {
num += exp[i];
}
else if (num != "") {
postfix += num + " ";
num = "";
}
if (exp[i] == '(') {
op.push(exp[i]);
}
else if (exp[i] == ')') {
while (!op.empty() && op.top() != '(') {
postfix += op.top();
op.pop();
}
if (!op.empty()) {
op.pop();
}
}
else if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/') {
while (!op.empty() && op.top() != '(' && priority(op.top()) >= priority(exp[i])) {
postfix += op.top();
op.pop();
}
op.push(exp[i]);
}
}
postfix += num;
while (!op.empty()) {
postfix += op.top();
op.pop();
}
}
int calculate(char sign, int a, int b) {
if (sign == '+') {
return a + b;
}
if (sign == '-') {
return a - b;
}
if (sign == '/') {
return a / b;
}
if (sign == '*') {
return a * b;
}
}
int evaluatePostfix() {
stack<int> values;
int nr = NOT_SET;
for (int i = 0; i < postfix.length(); ++i) {
if (postfix[i] >= '0' && postfix[i] <= '9') {
if (nr == NOT_SET)
nr = 0;
nr = nr * 10 + (postfix[i] - '0');
}
else if (nr != NOT_SET){
values.push(nr);
nr = NOT_SET;
}
if (postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/') {
int v1 = values.top();
values.pop();
int v2 = values.top();
values.pop();
values.push(calculate(postfix[i], v2, v1));
}
}
return values.top();
}
int main()
{
fin >> exp;
createPostFixExpression();
fout << evaluatePostfix() << "\n";
return 0;
}