Cod sursa(job #3375269)

Utilizator ultra980Alex Stan ultra980 Data 11 noiembrie 2026 11:54:43
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <cctype>
#include <string>
#include <stack>
using namespace std;

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

string expr;
int n;

stack<int> nums;
stack<char> ops;

int prec[256];

void init_arr() {
  prec['+'] = prec['-'] = 1;
  prec['*'] = prec['/'] = 2;
}

void read_input() {
  fin >> expr;
  n = expr.size();
}

int read_num(int &i) {
  int num = 0;

  while (i < n && isdigit(expr[i])) {
    num = num * 10 + expr[i] - '0';
    ++i;
  }

  --i;
  
  return num;
}

inline static int eval(int op, int l, int r) {
  switch (op) {
    case '+':
      return l + r;
    case '-':
      return l - r;
    case '*':
      return l * r;
    case '/':
      return l / r;
  }
  return 0;
}

void pop_operator() {
  char op = ops.top(); ops.pop();
  int l, r;
  r = nums.top(); nums.pop();
  l = nums.top(); nums.pop();

  nums.push(eval(op, l, r));
}

int parse_input() {
  for (int i = 0; i < n; ++i) {
    char ch = expr[i];
    
    if (isdigit(ch)) {
      nums.push(read_num(i));
    } else if (ch == '(') {
      ops.push('(');
    } else if (ch == ')') {
      while (ops.top() != '(') {
        pop_operator();
      }
      ops.pop();
    } else {
      while (!ops.empty() && prec[ops.top()] >= prec[ch]) {
        pop_operator();
      }
      ops.push(ch);
    }
  }

  while (!ops.empty()) {
    pop_operator();
  }

  return nums.top();
}

int main() {
  init_arr();
  read_input();
  fout << parse_input() << '\n';
}