Guest User

Untitled

a guest
Jun 18th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. #include <cstdint>
  2. #include <cstdio>
  3. #include <initializer_list>
  4.  
  5. // Xoshiro256** 32bit
  6. static uint64_t rotl(const uint64_t x, int k) {
  7. return (x << k) | (x >> (64 - k));
  8. }
  9. static uint32_t rng() {
  10. static uint64_t s[4] = {123456789, 987654321, 999778844, 99999999};
  11. const uint64_t ret = rotl(s[1] * 5, 7) * 9;
  12. const uint64_t t = s[1] << 17;
  13. s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3];
  14. s[2] ^= t; s[3] = rotl(s[3], 45);
  15. return ret >> 32;
  16. }
  17.  
  18. // Treap
  19. struct node {
  20. node *l, *r;
  21. int val;
  22. uint32_t t;
  23.  
  24. node() = default;
  25. node(int v) : val(v) {
  26. l = r = nullptr;
  27. t = rng();
  28. }
  29. ~node() {
  30. delete l;
  31. delete r;
  32. }
  33. };
  34. typedef node *pnode;
  35.  
  36. pnode treap_merge(pnode left, pnode right) {
  37. if (!left) return right;
  38. if (!right) return left;
  39. if (left->t > right->t) {
  40. left->r = treap_merge(left->r, right);
  41. return left;
  42. }
  43. right->l = treap_merge(left, right->l);
  44. return right;
  45. }
  46.  
  47. void treap_split(pnode root, int k, pnode &left, pnode &right) {
  48. if (!root) {
  49. left = nullptr;
  50. right = nullptr;
  51. } else if (root->val < k) {
  52. treap_split(root->r, k, root->r, right);
  53. left = root;
  54. } else {
  55. treap_split(root->l, k, left, root->l);
  56. right = root;
  57. }
  58. }
  59.  
  60. void printAll(pnode a) {
  61. if (!a) return;
  62. printAll(a->l);
  63. printf("%d ", a->val);
  64. printAll(a->r);
  65. }
  66.  
  67. class Treap {
  68. pnode root = nullptr;
  69. public:
  70. void insert(int p) {
  71. pnode left, right;
  72. treap_split(root, p, left, right);
  73. root = treap_merge(treap_merge(left, new node(p)), right);
  74. }
  75.  
  76. void remove(int p) {
  77. pnode left, mid, right;
  78. treap_split(root, p, left, mid);
  79. treap_split(mid, p + 1, mid, right);
  80. root = treap_merge(left, right);
  81. delete mid;
  82. }
  83.  
  84. void print() {
  85. printf("[ ");
  86. printAll(root);
  87. printf("]");
  88. }
  89. };
  90.  
  91. int main() {
  92. Treap tr;
  93.  
  94. for (const auto& x : {1, 9, 3, 4, 7, 6, 8, 2}) tr.insert(x);
  95. for (const auto& x : {7, 3}) tr.remove(x);
  96. tr.print(); // [ 1 2 4 6 8 9 ]
  97. }
Add Comment
Please, Sign In to add comment