Cod sursa(job #3294038)

Utilizator Robi27Baciu Roberto Robi27 Data 15 aprilie 2025 13:03:51
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.64 kb
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;

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

bool isOperator(char c) {
  return c == '+' || c == '-' || c == '*' || c == '/';
}

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

int applyOp(int a, int b, char op) {
  switch (op) {
    case '+': return a + b;
    case '-': return a - b;
    case '*': return a * b;
    case '/': return a / b;
  }
  return 0;
}

int convert(const string& expr) {
    stack<int> values;
    stack<char> operators;

    for (size_t i = 0; i < expr.size(); i++) {
        if (expr[i] == ' ') 
            continue;
        
        if (expr[i] == '(') {
            operators.push(expr[i]);
        }
        
        else if (isdigit(expr[i])) {
            int val = 0;
            while (i < expr.size() && isdigit(expr[i])) {
                val = (val * 10) + (expr[i] - '0');
                i++;
            }
            i--;
            values.push(val);
        }
        
        else if (expr[i] == ')') {
            while (!operators.empty() && operators.top() != '(') {
                int val2 = values.top(); values.pop();
                int val1 = values.top(); values.pop();
                
                char op = operators.top();
                operators.pop();
                
                values.push(applyOp(val1, val2, op));
            }
            if (!operators.empty())
                operators.pop();  // Remove '('
        }
        
        else if (isOperator(expr[i])) {
            while (!operators.empty() && operators.top() != '(' && 
                   ordine(operators.top()) >= ordine(expr[i])) {
                int val2 = values.top(); values.pop();
                int val1 = values.top(); values.pop();
                
                char op = operators.top();
                operators.pop();
                
                values.push(applyOp(val1, val2, op));
            }
            operators.push(expr[i]);
        }
    }
    
    while (!operators.empty()) {
        int val2 = values.top(); values.pop();
        int val1 = values.top(); values.pop();
        
        char op = operators.top();
        operators.pop();
        
        values.push(applyOp(val1, val2, op));
    }
    
    return values.top();
}

int main() {

    string expression;
    getline(fin, expression);

    try {
      int result = convert(expression);
      fout << result;
    } catch (const std::exception& e) {
      std::cerr << "Eroare: " << e.what() << "\n";
      fout << "Eroare la evaluarea expresiei";
    }

  fin.close();
  fout.close();
  return 0;
}