File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ //
2+ // Convert infix notation to postfix notation
3+ //
4+ // Description:
5+ // 1 * 2 + 3 * (4 + 5) <- infix notation
6+ // 1 2 * 3 4 5 + * + <- postfix notation
7+ // Postfix notation is easy to evaluate.
8+ //
9+ // Algorithm:
10+ // Shunting-yard algorithm by Dijkstra.
11+ //
12+ // Verified:
13+ // SPOJ 4: ONP - Transform the Expression
14+ //
15+
16+ #include < iostream>
17+ #include < stack>
18+ #include < vector>
19+ #include < cstdio>
20+ #include < algorithm>
21+ #include < functional>
22+ #include < sstream>
23+
24+ using namespace std ;
25+
26+ string infix_to_postfix (string s) {
27+ s += ' _' ; // terminal symbol
28+ stringstream ss;
29+ vector<char > op = {' _' };
30+ auto rank = [](char c) { return string (" (^/*-+)" ).find (c); };
31+ for (char c: s) {
32+ if (isalnum (c)) ss << c;
33+ else {
34+ for (; op.back () != ' (' ; op.pop_back ()) {
35+ if (rank (op.back ()) >= rank (c)) break ;
36+ ss << op.back ();
37+ }
38+ if (c == ' )' ) op.pop_back ();
39+ else op.push_back (c);
40+ }
41+ }
42+ return ss.str ();
43+ }
44+
45+ int main () {
46+ int ncase; scanf (" %d" , &ncase);
47+ for (int icase = 0 ; icase < ncase; ++icase) {
48+ char s[1024 ]; scanf (" %s" , s);
49+ printf (" %s\n " , infix_to_postfix (s).c_str ());
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments