Advertisement
Raslboyy

2782

Oct 11th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstdlib>
  4. #include <ctime>
  5.  
  6. using namespace std;
  7.  
  8. struct Node
  9. {
  10.     Node* l;
  11.     Node* r;
  12.     int key;
  13.     int prior;
  14.     Node(int key, int prior) : key(key), prior(prior), l(nullptr), r(nullptr) {}
  15. };
  16.  
  17. Node* root = nullptr;
  18.  
  19. Node* merge(Node* t1, Node* t2) {
  20.     if (t2 == nullptr) return t1;
  21.     if (t1 == nullptr) return t2;
  22.     if (t1->prior > t2->prior) {
  23.         t1->r = merge(t1->r, t2);
  24.         return t1;
  25.     }
  26.     else {
  27.         t2->l = merge(t1, t2->l);
  28.         return t2;
  29.     }
  30. }
  31.  
  32. pair<Node*, Node*> split(Node* t, int val) {
  33.     if (t == nullptr) return make_pair(nullptr, nullptr);
  34.     if (val > t->key) {
  35.         auto newT = split(t->r, val);
  36.         t->r = newT.first;
  37.         return make_pair(t, newT.second);
  38.     }
  39.     else {
  40.         auto newT = split(t->l, val);
  41.         t->l = newT.second;
  42.         return make_pair(newT.first, t);
  43.     }
  44. }
  45.  
  46. int GetMin(Node* t) {
  47.     if (t == nullptr) return -1;
  48.     if (t->l == nullptr) return t->key;
  49.     return GetMin(t->l);
  50. }
  51.  
  52. void insert(Node* cur, int val) {
  53.     auto p = split(root, val);
  54.     if (GetMin(p.second) != val)
  55.         root = merge(merge(p.first, new Node(val, ((rand() << 16) | rand()))), p.second);
  56.     else root = merge(p.first, p.second);
  57. }
  58.  
  59. int next(int val) {
  60.     auto p = split(root, val);
  61.     int a = GetMin(p.second);
  62.     root = merge(p.first, p.second);
  63.     return a;
  64. }
  65.  
  66. int main() {
  67.     ifstream fin("input.txt");
  68.     ofstream fout("output.txt");
  69.     srand(time(NULL));
  70.  
  71.     int n; bool f = 0; int prev = 0;
  72.     fin >> n;
  73.     for (int i = 0; i < n; i++) {
  74.         char ch; int a; fin >> ch >> a;
  75.         if (ch == '+') {
  76.             insert(root, (a + prev * f) % (int)1e9);
  77.             f = 0;
  78.         }
  79.         else {
  80.             f = 1;
  81.             prev = next(a);
  82.             fout << prev << endl;
  83.         }
  84.     }
  85.  
  86.     fin.close();
  87.     fout.close();
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement