-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinMaxArithmeticExpression.cpp
116 lines (112 loc) · 2.59 KB
/
MinMaxArithmeticExpression.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <iostream>
#include <stack>
#include <sstream>
#include<string>
#include <queue>
using namespace std;
bool isOperator(const string & token) {
return token == "+" || token == "-" || token == "*" || token == "/" || token == "min" || token == "max";
}
bool isDigit(const string & token) {
return token <= "9" && token >= "0";
}
int getPriority(const string & token) {
if (token == "+" || token == "-") return 1;
if (token == "*" || token == "/") return 2;
if (token == "min" || token == "max") return 3;
return 0;
}
int min(int a, int b) {
return (a > b ? b : a);
}
int max(int a, int b) {
return (a > b ? a : b);
}
string rpn(string input) {
string postfix = "";
string output = "", token;
stack < string > s;
istringstream iss(input);
while (iss >> token) {
if (isDigit(token)) {
postfix += token;
postfix += " ";
} else if (isOperator(token)) {
while (!s.empty() && getPriority(s.top()) >= getPriority(token)) {
postfix += s.top();
postfix += " ";
s.pop();
}
s.push(token);
} else if (token == "(") {
s.push(token);
} else if (token == ")") {
while (!s.empty() && s.top() != "(") {
postfix += s.top();
postfix += " ";
s.pop();
}
s.pop();
} else if (token == ",") {
while (s.top() != "(") {
postfix += s.top();
postfix += " ";
s.pop();
}
}
}
while (!s.empty()) {
postfix += s.top();
postfix += " ";
s.pop();
}
return postfix;
}
int calculate(string input) {
queue < string > queue;
stack < int > numbers;
int a, b;
istringstream iss(input);
string token;
while (iss >> token) {
queue.push(token);
}
while (queue.size() != 0) {
if (!isOperator(queue.front())) {
numbers.push(stoi(queue.front()));
queue.pop();
} else {
a = numbers.top();
numbers.pop();
b = numbers.top();
numbers.pop();
if (queue.front() == "min") {
numbers.push(min(a, b));
queue.pop();
} else if (queue.front() == "max") {
numbers.push(max(a, b));
queue.pop();
} else if (queue.front() == "+") {
numbers.push(a + b);
queue.pop();
} else if (queue.front() == "-") {
numbers.push(b - a);
queue.pop();
} else if (queue.front() == "*") {
numbers.push(a * b);
queue.pop();
} else {
numbers.push(b / a);
queue.pop();
}
}
}
return numbers.top();
}
int main() {
string s, token;
getline(cin, s);
string ans = rpn(s);
cout << calculate(ans);
return 0;
}