Advertisement
Saleh127

UVA 727 / Infix to Postfix - Implementation

Nov 20th, 2021
574
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. /***
  2.  created: 2021-11-20-14.30.04
  3. ***/
  4.  
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. #define ll long long
  8. #define get_lost_idiot return 0
  9. #define nl '\n'
  10.  
  11. int main()
  12. {
  13.     ios_base::sync_with_stdio(0);
  14.     cin.tie(0);
  15.     cout.tie(0);
  16.  
  17.  
  18.     map<string,ll>p;
  19.  
  20.     p["+"]=p["-"]=1;
  21.     p["*"]=p["/"]=2;
  22.  
  23.     string a;
  24.  
  25.     int tt;
  26.     cin>>tt;
  27.  
  28.     cin.ignore();
  29.     cin.ignore();
  30.  
  31.     for(int cs=1; cs<=tt; cs++)
  32.     {
  33.          string ans="";
  34.  
  35.          stack<string>x;
  36.  
  37.          while(getline(cin,a))
  38.          {
  39.               if(a.size()==0) break;
  40.  
  41.  
  42.               if(a[0]>='0' && a[0]<='9') ans+=a;
  43.  
  44.               else if(a[0]==')')
  45.               {
  46.                    while(x.empty()==false && x.top()!="(")
  47.                    {
  48.                         ans+=x.top();
  49.                         x.pop();
  50.                    }
  51.  
  52.                    if(x.empty()==false) x.pop();
  53.               }
  54.               else if(a[0]=='(')
  55.               {
  56.                    x.push(a);
  57.               }
  58.               else
  59.               {
  60.                    while(x.empty()==false && (x.top()=="*" || x.top()=="/"))
  61.                    {
  62.                         ans+=x.top();
  63.                         x.pop();
  64.                    }
  65.                    if(x.empty()==false && p[a]==p[x.top()])
  66.                    {
  67.                         ans+=x.top();
  68.                         x.pop();
  69.                    }
  70.                    x.push(a);
  71.               }
  72.          }
  73.  
  74.          while(x.empty()==false)
  75.          {
  76.               ans+=x.top();
  77.               x.pop();
  78.          }
  79.          cout<<ans<<nl;
  80.  
  81.          if(cs!=tt) cout<<nl;
  82.     }
  83.  
  84.  
  85.     get_lost_idiot;
  86. }
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement