fork(1) download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int isOperator(char ch)
  5. {
  6. if(ch=='^'||ch=='/'||ch=='*'||ch=='+'||ch=='-'||ch=='('||ch==')')
  7. return 1;
  8. else
  9. return 0;
  10. }
  11.  
  12. int getPrecedency(char ch)
  13. {
  14. if(ch=='^')
  15. return 5;
  16. else if(ch=='/'||ch=='*')
  17. return 4;
  18. else if(ch=='+'||ch=='-')
  19. return 3;
  20. else
  21. return 0;
  22. }
  23.  
  24. int main()
  25. {
  26. int t;
  27. cin>>t;
  28. while(t--)
  29. {
  30. int i=0,top=0;
  31. char sta[400];
  32. char expr[401];
  33. cin>>expr;
  34. while(expr[i])
  35. {
  36. if(!isOperator(expr[i]))
  37. cout<<expr[i];
  38.  
  39. else if(isOperator(expr[i]))
  40. {
  41. if(top==0||sta[top-1]=='('||expr[i]=='(')
  42. {
  43. sta[top]=expr[i];
  44. top++;
  45. }
  46. else if(expr[i]==')')
  47. {
  48. while(sta[top-1]!='(' && top>0)
  49. {
  50. cout<<sta[top-1];
  51. top--;
  52. }
  53. top--;
  54. }
  55. else if(getPrecedency(expr[i])>getPrecedency(sta[top-1]))
  56. {
  57. sta[top]=expr[i];
  58. top++;
  59. }
  60. else if(getPrecedency(expr[i])<=getPrecedency(sta[top-1]))
  61. {
  62. while(getPrecedency(expr[i])<=getPrecedency(sta[top-1])&& top>0)
  63. {
  64. cout<<sta[top-1];
  65. top--;
  66. }
  67. sta[top]=expr[i];
  68. top++;
  69. }
  70. }
  71. i++;
  72. }
  73. while(top>0)
  74. {
  75. cout<<sta[top-1];
  76. top--;
  77. }
  78. cout<<endl;
  79. }
  80. return 0;
  81. }
Success #stdin #stdout 0s 3348KB
stdin
3
(A+(B*C))
((A+B)*(Z+X))
((A+T)*((B+(A+C))^(C+D)))
stdout
ABC*+
AB+ZX+*
AT+BAC++CD+^*