Advertisement
smatskevich

Lesson5

Oct 24th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <random>
  3.  
  4. using namespace std;
  5.  
  6. struct TreapNode {
  7.   int Data;
  8.   int Priority = rand();
  9.   TreapNode* Left = nullptr;
  10.   TreapNode* Right = nullptr;
  11.   int Count = 1;
  12.   explicit TreapNode(int data) : Data(data) {}
  13. };
  14.  
  15. int Count(TreapNode* node) { return node ? node->Count : 0; }
  16. void Update(TreapNode* node) { node->Count = 1 + Count(node->Left) + Count(node->Right); }
  17.  
  18. pair<TreapNode*, TreapNode*> Split(TreapNode* node, int count) {
  19.   if (!node) return {nullptr, nullptr};
  20.   if (Count(node->Left) >= count) {
  21.     auto [t1, t2] = Split(node->Left, count);
  22.     node->Left = t2;
  23.     Update(node);
  24.     return {t1, node};
  25.   } else {
  26.     auto [t1, t2] = Split(node->Right, count - 1 - Count(node->Left));
  27.     node->Right = t1;
  28.     Update(node);
  29.     return {node, t2};
  30.   }
  31. }
  32.  
  33. TreapNode* Merge(TreapNode* t1, TreapNode* t2) {
  34.   if (!t1 || !t2) return t1 ? t1 : t2;
  35.   if (t1->Priority > t2->Priority) {
  36.     t1->Right = Merge(t1->Right, t2);
  37.     Update(t1);
  38.     return t1;
  39.   } else {
  40.     t2->Left = Merge(t1, t2->Left);
  41.     Update(t2);
  42.     return t2;
  43.   }
  44. }
  45.  
  46. void Insert(TreapNode*& root, int data, int pos) {
  47.   auto [t1, t2] = Split(root, pos);
  48.   TreapNode* node = new TreapNode(data);
  49.   root = Merge(Merge(t1, node), t2);
  50. }
  51.  
  52. void Print(TreapNode* node, string prefix = "") {
  53.   if (node == nullptr) return;
  54.   Print(node->Right, prefix + "  ");
  55.   cout << prefix << node->Data << "\n";
  56.   Print(node->Left, prefix + "  ");
  57. }
  58.  
  59. int main() {
  60.   srand(24);
  61.   TreapNode* root = nullptr;
  62.   Insert(root, 28, 0);
  63.   Print(root);
  64.   cout << "-----\n";
  65.   Insert(root, 43, 1);
  66.   Print(root);
  67.   cout << "-----\n";
  68.   Insert(root, 12, 0);
  69.   Print(root);
  70.   cout << "-----\n";
  71.   Insert(root, 30, 2);
  72.   Print(root);
  73.   cout << "-----\n";
  74.   Insert(root, 50, 4);
  75.   Print(root);
  76.   return 0;
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement