Cod sursa(job #3358964)

Utilizator octavP18Podan Octvavin octavP18 Data 22 iunie 2026 13:40:30
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>

#include <fstream>

#include <map>

#include <algorithm>

#include <vector>

#include <stack>

using namespace std;

#define all(x) x.begin(), x.end()
#define fs first
#define sc second

using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

bool isDigit(char x) {
	return ('0' <= x) and (x <= '9');
}

string expr;
stack<int> num;
stack<char> op;

int prioritate(char op) {
	if (op == '+' || op == '-') return 1;
	if (op == '*' || op == '/') return 2;
	return 0;
}

int solve(int x, int y, char op) {
	if (op == '+') return x + y;
	if (op == '-') return x - y;
	if (op == '/') return x / y;
	if (op == '*') return x * y;
}

int main() {

	fin >> expr;
	for (int i = 0; i < expr.size(); ++i) {
		if (isDigit(expr[i])) {
			int val = 0;
			while (i < expr.size() and isDigit(expr[i])) {
				val = val * 10 + (expr[i] - '0');
				++i;
			}
			--i;
			num.push(val);
		}
		else if (expr[i] == '(') op.push('(');
		else if (expr[i] == ')') {
			while (op.size() and op.top() != '(') {
				int y = num.top(); num.pop();
				int x = num.top(); num.pop();
				char semn = op.top(); op.pop();
				num.push(solve(x, y, semn));
			}
			op.pop();
		}
		else {
			while (op.size() and prioritate(op.top()) >= prioritate(expr[i])) {
				int y = num.top(); num.pop();
				int x = num.top(); num.pop();
				char semn = op.top(); op.pop();
				num.push(solve(x, y, semn));
			}
			op.push(expr[i]);
		}
	}
	while (op.size()) {
		int y = num.top(); num.pop();
		int x = num.top(); num.pop();
		char semn = op.top(); op.pop();
		num.push(solve(x, y, semn));
	}
	fout << num.top();
}