Skip to content

Instantly share code, notes, and snippets.

@kira924age
Last active December 3, 2017 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kira924age/f86c1761323cbe63d099e98e1ed64c62 to your computer and use it in GitHub Desktop.
Save kira924age/f86c1761323cbe63d099e98e1ed64c62 to your computer and use it in GitHub Desktop.
#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