Cod sursa(job #3233199)

Utilizator MirceaDonciuLicentaLicenta Mircea Donciu MirceaDonciuLicenta Data 2 iunie 2024 19:17:15
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.76 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <queue>
#include <sstream>
#include <cctype>

using namespace std;

// Function to define operator precedence
int precedence(char op) {
    if (op == '+' || op == '-') return 1;
    if (op == '*' || op == '/') return 2;
    return 0;
}

// Function to perform arithmetic operations
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;
}

// Function to convert infix expression to postfix expression (RPN)
queue<string> infixToPostfix(const string &exp) {
    stack<char> operators;
    queue<string> output;
    int n = exp.length();

    for (int i = 0; i < n; i++) {
        if (isdigit(exp[i])) {
            string num;
            while (i < n && isdigit(exp[i])) {
                num += exp[i++];
            }
            i--;
            output.push(num);
        } else if (exp[i] == '(') {
            operators.push(exp[i]);
        } else if (exp[i] == ')') {
            while (!operators.empty() && operators.top() != '(') {
                output.push(string(1, operators.top()));
                operators.pop();
            }
            operators.pop();
        } else if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/') {
            while (!operators.empty() && precedence(operators.top()) >= precedence(exp[i])) {
                output.push(string(1, operators.top()));
                operators.pop();
            }
            operators.push(exp[i]);
        }
    }

    while (!operators.empty()) {
        output.push(string(1, operators.top()));
        operators.pop();
    }

    return output;
}

// Function to evaluate a postfix expression (RPN)
int evaluatePostfix(queue<string> &tokens) {
    stack<int> values;
    while (!tokens.empty()) {
        string token = tokens.front();
        tokens.pop();
        if (isdigit(token[0])) {
            values.push(stoi(token));
        } else {
            int val2 = values.top();
            values.pop();
            int val1 = values.top();
            values.pop();
            values.push(applyOp(val1, val2, token[0]));
        }
    }
    return values.top();
}

int main() {
    ifstream infile("evaluare.in");
    ofstream outfile("evaluare.out");

    if (!infile || !outfile) {
        cerr << "Error opening file" << endl;
        return 1;
    }

    string expression;
    getline(infile, expression);

    queue<string> postfix = infixToPostfix(expression);
    int result = evaluatePostfix(postfix);

    outfile << result << endl;

    infile.close();
    outfile.close();

    return 0;
}