35657

Untitled

May 31st, 2024
676
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <fstream>
  4.  
  5. class StackMaxEffective {
  6.  
  7. public:
  8.  
  9.     void push(const int element) {
  10.         elements_.push_back(element);
  11.  
  12.         max_elements_.empty() ? max_elements_.push_back(element) : max_elements_.push_back(std::max(element, max_elements_.back()));
  13.     }
  14.  
  15.     void pop() {
  16.         if (elements_.empty()) {
  17.             std::cout << "error" << std::endl;
  18.         }
  19.         else {
  20.             elements_.pop_back();
  21.             max_elements_.pop_back();
  22.         }
  23.     }
  24.  
  25.     void get_max() {
  26.         if (elements_.empty()) {
  27.             std::cout << "None" << std::endl;
  28.         }
  29.         else {
  30.             std::cout << max_elements_.back() << std::endl;
  31.         }
  32.     }
  33.  
  34.     void top() {
  35.         if (elements_.empty()) {
  36.             std::cout << "error" << std::endl;
  37.         }
  38.         else {
  39.             std::cout << elements_.back() << std::endl;
  40.         }
  41.     }
  42.  
  43. private:
  44.  
  45.     std::vector<int> elements_;
  46.     std::vector<int> max_elements_;
  47. };
  48.  
  49. int main() {
  50.  
  51.     std::ifstream fin("input.txt");
  52.  
  53.     std::string command;
  54.     int count, num;
  55.  
  56.     fin >> count;
  57.  
  58.     StackMaxEffective stack;
  59.  
  60.     for (int i = 0; i < count; i++) {
  61.         fin >> command;
  62.         if (command == "pop") {
  63.             stack.pop();
  64.         }
  65.         if (command == "push") {
  66.             fin >> num;
  67.             stack.push(num);
  68.         }
  69.         if (command == "get_max") {
  70.             stack.get_max();
  71.         }
  72.         if (command == "top") {
  73.             stack.top();
  74.         }
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment