Pagini recente » Cod sursa (job #199895) | Cod sursa (job #1616025) | Diferente pentru autumn-warmup-2007/solutii/runda-2 intre reviziile 56 si 46 | Cod sursa (job #3277890) | Cod sursa (job #3202236)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
stack<char> ops;
stack<int> values;
int calculate(int a, int b, char op) {
if (op == '+') return a + b;
if (op == '-') return a - b;
if (op == '*') return a * b;
if (op == '/') return a / b;
}
int predecence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
int evaluate(char tokens[]) {
for (int i = 0; i < strlen(tokens); i++) {
if (isdigit(tokens[i])) {
int val = 0;
while (isdigit(tokens[i]) && i < strlen(tokens)) {
val = val*10 + (tokens[i]-'0');
i++;
}
i--;
values.push(val);
}
else if (tokens[i] == '(') ops.push('(');
else if (tokens[i] == ')') {
while (!ops.empty() && ops.top() != '(') {
int x = values.top();
values.pop();
int y = values.top();
values.pop();
char op = ops.top();
ops.pop();
int ans = calculate(y, x, op);
values.push(ans);
}
if (!ops.empty()) ops.pop();
}
else {
while (!ops.empty() && predecence(tokens[i]) <= predecence(ops.top())) {
int x = values.top();
values.pop();
int y = values.top();
values.pop();
char op = ops.top();
ops.pop();
int ans = calculate(y, x, op);
values.push(ans);
}
ops.push(tokens[i]);
}
}
while (!ops.empty()) {
int x = values.top();
values.pop();
int y = values.top();
values.pop();
char op = ops.top();
ops.pop();
int ans = calculate(y, x, op);
values.push(ans);
}
return values.top();
}
int main() {
char expresie[100001];
fin>>expresie;
int rez = evaluate(expresie);
fout<<rez;
return 0;
}