-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path727_equation.cpp
81 lines (76 loc) · 1.44 KB
/
727_equation.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
// Xiaoyan Wang 9/16/2016
#include <iostream>
// #include <vector>
#include <string>
#include <stack>
#include <cctype>
using namespace std;
bool isop(const char& c);
int opval(const char& c);
int main() {
ios::sync_with_stdio(false);
int cases;
cin >> cases;
cin.ignore();
cin.ignore();
// Notice: \10 is equivalent to \n
string line;
while(cases--) {
string result;
result.reserve(50);
stack<char> operation;
while(getline(cin, line)) {
if(line == "")
break;
char input = line[0];
if(isdigit(input))
result.push_back(input);
else if(input == '(')
operation.push(input);
else if(input == ')') {
while(operation.top() != '(') {
result.push_back(operation.top());
operation.pop();
}
operation.pop();
}
else if(isop(input)) {
while(!operation.empty() && opval(input) <= opval(operation.top())) {
result.push_back(operation.top());
operation.pop();
}
operation.push(input);
}
}
while(!operation.empty()) {
result.push_back(operation.top());
operation.pop();
}
cout << result << '\n';
if(cases)
cout << '\n';
}
cout << flush;
return 0;
}
inline bool isop(const char& c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int opval(const char& c) {
switch(c) {
case '+':
case '-':
return 1;
break; //no necessary
case '*':
case '/':
return 2;
break;
case '(':
case ')':
return 0;
break;
default:
return -1;
}
}