fork download
  1. #include<bits/stdc++.h>
  2. using namespace std ;
  3.  
  4. int precedence(char c){
  5. if(c == '*' || c == '/') return 5 ;
  6. if(c == '+' || c == '-') return 4 ;
  7. return 0 ;
  8. }
  9.  
  10. void solve(string s){
  11. stack<char> st ;
  12. string res = "";
  13. for(int i = 0 ; i < s.size();i++){
  14. if(isalpha(s[i])) res += s[i];
  15. else if(s[i] == '(') st.push(s[i]);
  16. else if(s[i] == ')'){
  17. while(!st.empty() && st.top() != '('){
  18. res += st.top();
  19. st.pop();
  20. }
  21. st.pop();
  22. }
  23. else{
  24. while(!st.empty() && precedence(st.top()) >= precedence(s[i])){
  25. res += st.top();
  26. st.pop();
  27. }
  28. st.push(s[i]);
  29. }
  30. }
  31. while(!st.empty()){
  32. res += st.top();
  33. st.pop();
  34. }
  35. cout << res ;
  36. }
  37.  
  38. int main(){
  39. ios::sync_with_stdio(false);
  40. cin.tie(nullptr);
  41. cout.tie(nullptr);
  42.  
  43. string s ; cin >> s;
  44. solve(s);
  45. }
Success #stdin #stdout 0s 5304KB
stdin
(A-(B+C))*(a+b*c)
stdout
ABC+-abc*+*