Ciemny_Cygan

N2O

Sep 16th, 2020 (edited)
738
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <stack>
  4. #include <ctype.h>
  5.  
  6. using namespace std;
  7.  
  8. string Spaced(string userString);
  9.  
  10. string Spaced(string userString)
  11. {
  12.     string spacedString = "";
  13.     int i1 = 0;
  14.     int i2 = 0;
  15.  
  16.     for (unsigned int i = 0; i < userString.length(); i++)
  17.     {
  18.         string s1 (1, userString[i]);
  19.         string s2 (1, userString[i + 1]);
  20.         i1 = userString[i];
  21.         i2 = userString[i + 1];
  22.        
  23.         if (!isdigit(i1) || !isdigit(i2))
  24.         {
  25.             spacedString += s1 + " ";
  26.         } else
  27.         {
  28.             spacedString += s1;
  29.         }
  30.     }
  31.  
  32.     return spacedString;
  33. }
  34.  
  35. string infixToPostfix(const string& infix) {
  36.     const string ops = "-+/*^";
  37.     stringstream ss;
  38.     stack<int> s;
  39.  
  40.     stringstream input(infix);
  41.     string token;
  42.     while (getline(input, token, ' ')) {
  43.         if (token.empty()) {
  44.             continue;
  45.         }
  46.  
  47.         char c = token[0];
  48.         size_t idx = ops.find(c);
  49.  
  50.         if (idx != string::npos) {
  51.             while (!s.empty()) {
  52.                 int prec2 = s.top() / 2;
  53.                 int prec1 = idx / 2;
  54.                 if (prec2 > prec1 || (prec2 == prec1 && c != '^')) {
  55.                     ss << ops[s.top()] << ' ';
  56.                     s.pop();
  57.                 } else break;
  58.             }
  59.             s.push(idx);
  60.         } else if (c == '(') {
  61.             s.push(-2);
  62.         } else if (c == ')') {
  63.             while (s.top() != -2) {
  64.                 ss << ops[s.top()] << ' ';
  65.                 s.pop();
  66.             }
  67.             s.pop();
  68.         } else {
  69.             ss << token << ' ';
  70.         }
  71.     }
  72.  
  73.     while (!s.empty()) {
  74.         ss << ops[s.top()] << ' ';
  75.         s.pop();
  76.     }
  77.  
  78.     return ss.str();
  79. }
  80.  
  81. int main() {
  82.  
  83.     int dump;
  84.     int t;
  85.     string userString;
  86.     cin >> t;
  87.  
  88.     string tab[t];
  89.  
  90.     for(int i=0; i<t; i++){
  91.         cin >> dump;
  92.         cin >> tab[i];
  93.     }
  94.  
  95.     for(int j=0; j<t; j++){
  96.         userString = tab[j];
  97.         string infix = Spaced(userString);
  98.         cout << infixToPostfix(infix) << '\n';
  99.     }
  100.  
  101.     return 0;
  102. }
Add Comment
Please, Sign In to add comment