Advertisement
Derga

Untitled

Aug 22nd, 2023
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <deque>
  3.  
  4. using namespace std;
  5.  
  6. struct DoubleQueue {
  7.     deque<int> first, second;
  8.  
  9.     void normalize() {
  10.         int target_first_size = (first.size() + second.size() + 1) / 2;
  11.  
  12.         if (first.size() < target_first_size) {
  13.             while (first.size() < second.size()) {
  14.                 first.push_back(second.front());
  15.                 second.pop_front();
  16.             }
  17.         } else {
  18.             while (first.size() > target_first_size) {
  19.                 second.push_front(first.back());
  20.                 first.pop_back();
  21.             }
  22.         }
  23.     }
  24.  
  25.     void push_back(int x) {
  26.         second.push_back(x);
  27.         normalize();
  28.     }
  29.  
  30.     void push_middle(int x) {
  31.         first.push_back(x);
  32.         normalize();
  33.     }
  34.  
  35.     int pop() {
  36.         int result = first.front();
  37.         first.pop_front();
  38.         normalize();
  39.         return result;
  40.     }
  41. };
  42.  
  43. int main() {
  44.     int n;
  45.     cin >> n;
  46.     DoubleQueue q;
  47.  
  48.     for (int i = 0; i < n; ++i) {
  49.         string query;
  50.         cin >> query;
  51.         if (query == "+") {
  52.             int x;
  53.             cin >> x;
  54.             q.push_back(x);
  55.         } else if (query == "*") {
  56.             int x;
  57.             cin >> x;
  58.             q.push_middle(x);
  59.         } else {
  60.             cout << q.pop() << "\n";
  61.         }
  62.     }
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement