fork(2) download
  1. #include <iostream>
  2. #include <string>
  3. #include <stack>
  4. #include <fstream>
  5.  
  6. using namespace std;
  7.  
  8. bool prec(char cur)
  9. {
  10. if( cur == '*' || cur == '/') return 1;
  11. if( cur == '+' || cur == '-') return 0;
  12. }
  13.  
  14. void reverse(string &s, int st, int en)
  15. {
  16. if( st <= en )
  17. {
  18. char ch = s[st];
  19. s[st] = s[en];
  20. s[en] = ch;
  21. reverse(s, ++st, --en);
  22. }
  23. }
  24.  
  25. void infix_to_postfix(string &s)
  26. {
  27. stack<char> output;
  28. stack<char> oper;
  29. int len = s.size();
  30.  
  31. for(int i = 0; i < len; ++i)
  32. {
  33. if( isdigit(s[i]))
  34. output.push(s[i]);
  35. else
  36. {
  37. if( s[i] == '(' )
  38. oper.push(s[i]);
  39. else if( s[i] == ')')
  40. {
  41. while( !oper.empty() && oper.top() != '(')
  42. {
  43. output.push(oper.top());
  44. oper.pop();
  45. }
  46. oper.pop();
  47. }
  48. else
  49. {
  50. if( !oper.empty() && oper.top() != '(' && oper.top() != ')')
  51. {
  52. while( !oper.empty() && (prec(s[i]) < prec(oper.top())) )
  53. {
  54. output.push(oper.top());
  55. oper.pop();
  56. }
  57. if( !oper.empty() && (prec(s[i]) == prec(oper.top())) )
  58. {
  59. output.push(oper.top());
  60. oper.pop();
  61. }
  62.  
  63. }
  64. oper.push(s[i]);
  65. }
  66. }
  67. }
  68. while(!oper.empty())
  69. {
  70. output.push(oper.top());
  71. oper.pop();
  72. }
  73.  
  74. string so;
  75. while(!output.empty())
  76. {
  77. so += output.top();
  78. output.pop();
  79. }
  80.  
  81. reverse(so, 0, so.size()-1);
  82. cout << so << endl;
  83. }
  84.  
  85. int main()
  86. {
  87.  
  88.  
  89. int test;
  90. cin >> test;
  91. cin.ignore();
  92. cin.ignore();
  93. char ch;
  94. string s, str;
  95.  
  96. int k = 0;
  97. while(k < test)
  98. {
  99. while( getline(cin, str) )
  100. {
  101. if(str.size() == 0 )
  102. break;
  103. s += str;
  104. }
  105.  
  106. k++;
  107. infix_to_postfix(s);
  108.  
  109. if( k != test)
  110. cout << endl;
  111. str.clear();
  112. s.clear();
  113. }
  114.  
  115. return 0;
  116. }
  117.  
Success #stdin #stdout 0s 2996KB
stdin
7

(
3
+
2
)
*
5

1
*
2
(
1
+
2
)
1
+
2

3
+
4
*
5
/
6

(
300
+
23
)
*
(
43
-
21
)
/
(
84
+
7
)

(
4
+
8
)
*
(
6
-
5
)
/
(
(
3
-
2
)
*
(
2
+
2
)
)

(
3
*
5
/
2
*
6
/
(
3
+
2
)
*
5
)
+
4

0
*
8
-
4
*
6
+
4
/
7
*
2
stdout
32+5*

1212+1*2+

345*6/+

30023+4321-*847+/

48+65-*32-22+*/

35*2/6*32+/5*4+

08*46*-47/2*+