Last active
December 3, 2017 02:09
-
-
Save kira924age/f86c1761323cbe63d099e98e1ed64c62 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <stack> | |
#include <map> | |
#include <cstdlib> | |
#include <cctype> | |
using namespace std; | |
void str2arr(string s, string A[]) { | |
int n = 0; | |
string tmp = ""; | |
for (int i = 0; s[i] != '=' ; i++) { | |
if ('0' <= s[i] && s[i] <= '9') { | |
tmp += s[i]; | |
} | |
else { | |
if (tmp != "") { | |
A[n++] = tmp; | |
tmp = ""; | |
} | |
A[n++] = s[i]; | |
} | |
} | |
if (tmp != "") { A[n++] = tmp; } | |
A[n++] = "="; | |
} | |
void Generate_RPN(string A[], string B[]) { | |
map<string, int> table; | |
stack<string> St; | |
table["*"] = 1; | |
table["/"] = 1; | |
table["+"] = 0; | |
table["-"] = 0; | |
table["("] = -1; | |
table[")"] = -1; | |
int j = 0; | |
for (int i = 0; A[i] != "="; i++) { | |
if ('0' <= A[i][0] && A[i][0] <= '9') { | |
B[j++] = A[i]; | |
} | |
else if (A[i] == "(") { | |
St.push(A[i]); | |
} | |
else if (A[i] == ")") { | |
while (St.top() != "(") { | |
B[j++] = St.top(); St.pop(); | |
} | |
St.pop(); | |
} | |
else { | |
while ((!St.empty()) && (table[St.top()] >= table[A[i]])) { | |
B[j++] = St.top(); St.pop(); | |
} | |
St.push(A[i]); | |
} | |
} | |
while (!St.empty()) { | |
B[j++] = St.top(); St.pop(); | |
} | |
B[j] = "="; | |
} | |
int main() { | |
string A[100], B[100]; | |
string s; | |
cin >> s; | |
s += "="; | |
str2arr(s, A); | |
Generate_RPN(A, B); | |
for (int i = 0; B[i] != "="; i++) { | |
cout << B[i]; | |
cout << (B[i+1] == "=" ? "\n" : " "); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment