akela43

Untitled

Feb 20th, 2023
638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #### стек с максимумом
  2. #include <iostream>
  3. #include <sstream>
  4. #include <string>
  5. class Stack
  6. {
  7. private:
  8.     struct X {
  9.         int value;
  10.         int localMax;
  11.     };
  12.  
  13.     X *data_;
  14.     int size;
  15.     int top = -1;
  16. public:
  17.     Stack(int n): data_(new X[n]), size(n),  top(-1) { }
  18.     void push(int value)
  19.     {
  20.         ++top;
  21.         if (top == -1)
  22.         {
  23.             data_[top].value = value;
  24.             data_[top].localMax = value;
  25.         }
  26.         else
  27.         {
  28.             data_[top].value = value;
  29.             data_[top].localMax = data_[top-1].localMax < value ? value : data_[top-1].localMax;
  30.         }
  31.        
  32.     }
  33.     void pop() {  --top; }
  34.    
  35.     int max() const {return data_[top].localMax;  }
  36. };
  37. void test1(std::istream &cin, std::ostream & cout)
  38. {
  39.     int n;
  40.     cin >> n;
  41.     Stack stack(n);
  42.     std::string command;
  43.     int value;
  44.     while (n--) {
  45.         cin>> command;
  46.         if (command == "push")
  47.         {
  48.             cin >>  value;
  49.             stack.push(value);
  50.         }
  51.         else if (command == "pop") { stack.pop();}
  52.         else if (command == "max") { cout << stack.max() << "\n"; }
  53.     }
  54. }
  55. int main(int argc, char *argv[])
  56. {
  57.     {
  58.         std::istringstream istr(std::string("5 push 1 push 2 max pop max"));
  59.         std::string answer;
  60.         std::ostringstream ostr(answer);
  61.         test1(istr, ostr);
  62.         std::cout << "ответ:\n" << ostr.str() << "\n";
  63.         std::cout << "верный ответ 2 1 \n";
  64.     }
  65.    
  66.     {
  67.         std::istringstream istr("10 push 2 push 3 push 9 push 7 push 2 max max max pop max");
  68.         test1(istr, std::cout);
  69.         std::cout << "верный ответ 9 9 9 9 \n";
  70.     }
  71.         {
  72.         std::istringstream istr("5 push 2 push 1 max pop max");
  73.         test1(istr, std::cout);
  74.         std::cout << "верный ответ 2 2 \n";
  75.     }
  76.    
  77.    
  78.    
  79. }
Advertisement
Add Comment
Please, Sign In to add comment