bor

В начало строя!

bor
Jul 26th, 2013
627
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <cstdio>
  2. #include <ctime>
  3. #include <cstdlib>
  4. #include <vector>
  5. using namespace std;
  6.  
  7. struct treap {
  8.   typedef treap* pTreap;
  9.   int heap;
  10.   int data;
  11.   int branch;
  12.   treap *left, *right;
  13.   treap(int d) {
  14.     heap = rand();
  15.     data = d;
  16.     branch = 1;
  17.     left = right = NULL;
  18.   }
  19.   void split(int i, pTreap& lil, pTreap& big) {
  20.     int myi = left == NULL ? 0 : left->branch;
  21.     lil = big = NULL;
  22.     if (myi < i) {
  23.       // move right
  24.       if (right != NULL) {
  25.         right->split(i - (myi + 1), right, big);
  26.       }
  27.       lil = this;
  28.     } else {
  29.       // move left
  30.       if (left != NULL) {
  31.                 left->split(i, lil, left);
  32.             }
  33.             big = this;
  34.     }
  35.     branch = (left == NULL ? 0 : left->branch) + (right == NULL ? 0 : right->branch) + 1;
  36.   }
  37. };
  38.  
  39. int branchOf(treap* a) { return a == NULL ? 0 : a->branch; }
  40.  
  41. treap* merge(treap* a, treap* b) {
  42.   if (a == NULL) { return b; }
  43.   if (b == NULL) { return a; }
  44.   if (a->heap > b->heap) {
  45.     a->right = merge(a->right, b);
  46.     a->branch = branchOf(a->left) + branchOf(a->right) + 1;
  47.     return a;
  48.   } else {
  49.     b->left = merge(a, b->left);
  50.     b->branch = branchOf(b->left) + branchOf(b->right) + 1;
  51.     return b;
  52.   }
  53. }
  54.  
  55. void print(treap* a) {
  56.   if (a != NULL) {
  57.     print(a->left);
  58.     printf("%d ", a->data);
  59.     print(a->right);
  60.   }
  61. }
  62.  
  63. int main() {
  64.   freopen("g.in", "r", stdin);
  65.   freopen("g.out", "w", stdout);
  66.   srand(time(NULL)), rand();
  67.   int n, m, i, a, b;
  68.   treap *root = NULL, *A, *B, *C;
  69.   scanf("%d%d", &n, &m);
  70.   for (i = 0; i < n; root = merge(root, new treap(++i))) { }
  71.   for (i = 0; i < m; ++i) {
  72.     // print(root); putchar('\n');
  73.     scanf("%d%d", &a, &b);
  74.     root->split(b, B, C);
  75.     if (B != NULL) {
  76.       B->split(a - 1, A, B);
  77.     } else {
  78.       A = NULL;
  79.     }
  80.     root = merge(B, merge(A, C));
  81.   }
  82.   print(root);
  83.   return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment