Cod sursa(job #2265839)

Utilizator icansmileSmileSmile icansmile Data 21 octombrie 2018 19:56:05
Problema Evaluarea unei expresii Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.56 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stack>
#include <cstdlib>
#include <sstream>

using namespace std;

int getPriority(string s) {
    if (s == "(") {
        return 0;
    }

    if (s == "+" || s == "-") {
        return 1;
    }

    return 2;
}

int main() {
    ifstream in("evaluare.in");
    ofstream out("evaluare.out");
    vector<string> reverseNotation;
    string input;
    stack<string> operandStack;

    in >> input;

    for (int i = 0; i < input.size(); i++) {
        if (isdigit(input[i])) {
            string temp = "";
            while (isdigit(input[i])) {
                temp += (char)(input[i]);
                i++;
            }
            reverseNotation.push_back(temp);
            i--;
        } else if (input[i] == '(') {
            operandStack.push("(");
        } else if (input[i] == ')') {
            while (operandStack.top() != "(") {
                reverseNotation.push_back(operandStack.top());
                operandStack.pop();
            }
            operandStack.pop();
        } else {
            string temp = "";
            temp += (char)(input[i]);

            while (!operandStack.empty() && getPriority(operandStack.top()) >= getPriority(temp)) {
                reverseNotation.push_back(operandStack.top());
                operandStack.pop();
            }

            operandStack.push(temp);
        }
    }

    while (!operandStack.empty()) {
        reverseNotation.push_back(operandStack.top());
        operandStack.pop();
    }

    int result = 0;
    stack<string> result_operand_stack;

    for (auto token : reverseNotation) {
        if (token == "+" || token == "*" || token == "-" || token == "/") {
            string first = result_operand_stack.top();
            result_operand_stack.pop();
            string second = result_operand_stack.top();
            result_operand_stack.pop();

            if (token == "+") {
                result = atoi(first.c_str()) + atoi(second.c_str());
            } else if (token == "*") {
                result = atoi(first.c_str()) * atoi(second.c_str());
            } else if (token == "-") {
                result = atoi(second.c_str()) - atoi(first.c_str());
            } else if (token == "/") {
                result = atoi(second.c_str()) / atoi(first.c_str());
            }

            ostringstream tmp;
            tmp << result;
            result_operand_stack.push(tmp.str());
        } else {
            result_operand_stack.push(token);
        }
    }

    out << result;

    in.close();
    out.close();

    return 0;
}