Cod sursa(job #3253363)

Utilizator BucsMateMate Bucs BucsMate Data 2 noiembrie 2024 13:18:54
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <string>

using namespace std;

ifstream input("evaluare.in");
ofstream output("evaluare.out");

int getNextNum(string &expression, int &pos)
{
    int result = 0;
    while(expression[pos] >= '0' && expression[pos] <= '9' && pos < expression.size()){
        result = 10*result + expression[pos] - '0';
        pos++;
    }
    pos--;
    return result;
}

void evaluateOperation(stack<int> &st_num, char operation)
{
    int num1 = st_num.top();
    st_num.pop();
    int num2 = st_num.top();
    st_num.pop();

    int result;
    if(operation == '+'){
        result = num2 + num1;
    }
    else if(operation == '-'){
        result = num2 - num1;
    }
    else if(operation == '*'){
        result = num2 * num1;
    }
    else{
        result = num2 / num1;
    }

    st_num.push(result);
}

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

int main()
{
    string expression;
    input >> expression;
    stack<int> st_num;
    stack<char> st_op;

    int pos = 0;
    while(pos < expression.size()){
        char next_char = expression[pos];

        if(next_char >= '0' && next_char <= '9'){
            st_num.push(getNextNum(expression, pos));
        }
        else if(next_char == '('){
            st_op.push(next_char);
        }
        else if(next_char == ')'){
            while(st_op.top() != '('){
                char operation = st_op.top();
                st_op.pop();
                evaluateOperation(st_num, operation);
            }
            st_op.pop();
        }
        else{
            while(!st_op.empty() && st_op.top() != '(' && precedence(st_op.top()) >= precedence(next_char)){
                evaluateOperation(st_num, st_op.top());
                st_op.pop();
            }
            st_op.push(next_char);
        }
        pos++;
    }

    while(!st_op.empty()){
        evaluateOperation(st_num, st_op.top());
        st_op.pop();
    }
    output << st_num.top();
    return 0;
}