Pagini recente » Cod sursa (job #3310974) | Cod sursa (job #3042409) | Cod sursa (job #1471240) | Cod sursa (job #3325631) | Cod sursa (job #3311098)
#include <iostream>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <iomanip>
using namespace std;
#define ll long long
string expression;
void ReadData() {
cin >> expression ;
}
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
int applyOp(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; // assumes no divide by zero
return 0;
}
int evaluate(string expr) {
stack<int> vals; // numbers
stack<char> ops; // operators
for (int i = 0; i < expr.size(); i++) {
char c = expr[i];
if (c == ' ') continue;
// parse numbers (could be multi-digit)
if (isdigit(c)) {
int val = 0;
while (i < expr.size() && isdigit(expr[i])) {
val = val * 10 + (expr[i] - '0');
i++;
}
vals.push(val);
i--; // step back
}
else if (c == '(') {
ops.push(c);
}
else if (c == ')') {
while (!ops.empty() && ops.top() != '(') {
int b = vals.top(); vals.pop();
int a = vals.top(); vals.pop();
char op = ops.top(); ops.pop();
vals.push(applyOp(a, b, op));
}
ops.pop(); // remove '('
}
else { // operator
while (!ops.empty() && precedence(ops.top()) >= precedence(c)) {
int b = vals.top(); vals.pop();
int a = vals.top(); vals.pop();
char op = ops.top(); ops.pop();
vals.push(applyOp(a, b, op));
}
ops.push(c);
}
}
// apply remaining ops
while (!ops.empty()) {
int b = vals.top(); vals.pop();
int a = vals.top(); vals.pop();
char op = ops.top(); ops.pop();
vals.push(applyOp(a, b, op));
}
return vals.top();
}
void Solve() {
cout << evaluate(expression) << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
int t = 1;
// cin >> t; // Uncomment for multiple test cases
while (t--) {
ReadData();
Solve();
}
return 0;
}