Pagini recente » Cod sursa (job #2771116) | Cod sursa (job #2974583) | Cod sursa (job #2154230) | Cod sursa (job #2602049) | Cod sursa (job #3331911)
#include<bits/stdc++.h>
using namespace std;
const int NMAX = 100005;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int priority(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
vector<string> ToReversePolishNotation(string &infix_operation) {
stack<char> operands;
vector<string> result;
int n = infix_operation.length();
for (int i = 0; i < n; i++) {\
if (isdigit(infix_operation[i])) {
string new_number;
while (i < n && isdigit(infix_operation[i]) ) {
new_number += infix_operation[i];
i++;
}
i--;
result.push_back(new_number);
}
else if (infix_operation[i] == '(') {
operands.push(infix_operation[i]);
}
else if (infix_operation[i] == ')') {
while (!operands.empty() && operands.top() != '(') {
result.push_back(string(1, operands.top()));
operands.pop();
}
operands.pop();
}
else {
while (!operands.empty() && priority(operands.top()) >= priority(infix_operation[i])) {
result.push_back(string(1, operands.top()));
operands.pop();
}
operands.push(infix_operation[i]);
}
}
while (!operands.empty()) {
result.push_back(string(1, operands.top()));
operands.pop();
}
return result;
}
long long operation(long long a, long long b, char op) {
if (op == '+') return a + b;
if (op == '-') return a - b;
if (op == '*') return a * b;
if (op == '/') return a / b;
return 0;
}
long long evaluate(string &infix_operation) {
vector<string> reverse_polish_notation_operation = ToReversePolishNotation(infix_operation);
stack<long long> numbers;
long long result = 0;
for (auto i : reverse_polish_notation_operation) {
if (isdigit(i[0])) {
numbers.push(stoll(i));
}
else {
long long a = numbers.top();
numbers.pop();
long long b = numbers.top();
numbers.pop();
numbers.push(operation(b, a, i[0]));
}
}
return numbers.top();
}
int main() {
string operation;
fin>>operation;
int result = evaluate(operation);
fout<<result<<endl;
return 0;
}