Cod sursa(job #3238319)

Utilizator AlinaFloreaFlorea Alina AlinaFlorea Data 24 iulie 2024 11:23:15
Problema Evaluarea unei expresii Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.55 kb
#include <fstream>
#include <stack>
#include <vector>
#include <string>

using namespace std;

ifstream f("evaluare.in");
ofstream g("evaluare.out");

string e;

int precedence(string op) {
    if (op == "+" || op == "-") return 1;
    if (op == "*" || op == "/") return 2;
    return 0;
}

vector<string> infixToPostfix(string str) {
    vector<string> result;
    stack<string> stack;
    //(1+1)*13+10/2
    int n = str.size();
    int i = 0;
    string nr = "";
    while (i < n) {
        if (isdigit(str[i])) {
            while(isdigit(str[i])) {
                nr += str[i];
                i++;
            }
            result.push_back(nr);
            nr = "";
        } else {
            string current = string(1,str[i]);
            if (current == "(") {
                stack.push(current);
            } else if (current == ")") {
                if (!stack.empty() && stack.top() != "(") {
                    result.push_back(stack.top());
                    stack.pop();
                }
                if (!stack.empty()) stack.pop(); // the (
            } else {
                if (!stack.empty() && precedence(current) <= precedence(stack.top())) {
                    result.push_back(stack.top());
                    stack.pop();
                } 
                stack.push(current);
            }
            i++;
        }
    }

    while (!stack.empty()) {
        if (stack.top() != "(")
        result.push_back(stack.top());
        stack.pop();
    }

    return result;
}

bool isOperator(string str) {
    if (str == "+" || str == "-" || str == "/" || str == "*")
        return true;
    return false;
}

int evaluation(vector<string> result) {
    int key = 0;
    stack<int> stack;
    for (auto str: result) {
        if (isOperator(str)) {
            int first = 0, second = 0;
            if (!stack.empty()) {
                first = stack.top();
                stack.pop();
            }
            if (!stack.empty()) {
                second = stack.top();
                stack.pop();
            }
            if (str == "+") {
                stack.push(first + second);
            } else if (str == "-") {
                stack.push(second - first);
            } else if (str == "*") {
                stack.push(first * second);
            } else if (str == "/") {
                stack.push(second / first);
            }
        } else {
            int nr = stoi(str);
            stack.push(nr);
        }
    }
    return stack.top();
}


int main() {

    f >> e;
    vector<string> result = infixToPostfix(e);
    g << evaluation(result);


}