|
| 1 | +// |
| 2 | +// Leftist Heap |
| 3 | +// |
| 4 | +// Description: |
| 5 | +// |
| 6 | +// Leftist heap is a heap data structure that allows |
| 7 | +// the meld (merge) operation in O(log n) time. |
| 8 | +// Use this for persistent heaps. |
| 9 | +// |
| 10 | +// Complexity: |
| 11 | +// |
| 12 | +// O(1) for top, O(log n) for push/pop/meld |
| 13 | +// |
| 14 | +// g++ -std=c++17 -O3 -fmax-errors=1 -fsanitize=undefined |
| 15 | +#include <bits/stdc++.h> |
| 16 | + |
| 17 | +using namespace std; |
| 18 | + |
| 19 | +#define fst first |
| 20 | +#define snd second |
| 21 | +#define all(c) ((c).begin()), ((c).end()) |
| 22 | +#define TEST(s) if (!(s)) { cout << __LINE__ << " " << #s << endl; exit(-1); } |
| 23 | + |
| 24 | +template <class T> |
| 25 | +struct LeftistHeap { |
| 26 | + struct Node { |
| 27 | + T key; |
| 28 | + Node *left = 0, *right = 0; |
| 29 | + int dist = 0; |
| 30 | + } *root = 0; |
| 31 | + static Node *merge(Node *x, Node *y) { |
| 32 | + if (!x) return y; |
| 33 | + if (!y) return x; |
| 34 | + if (x->key > y->key) swap(x, y); |
| 35 | + x->right = merge(x->right, y); |
| 36 | + if (!x->left || x->left->dist < x->dist) swap(x->left, x->right); |
| 37 | + x->dist = (x->right ? x->right->dist : 0) + 1; |
| 38 | + return x; |
| 39 | + } |
| 40 | + void push(T key) { root = merge(root, new Node({key})); } |
| 41 | + void pop() { root = merge(root->left, root->right); } |
| 42 | + T top() { return root->key; } |
| 43 | +}; |
| 44 | + |
| 45 | +// |
| 46 | +// Persistent Implementaiton. (allow copy) |
| 47 | +// |
| 48 | +template <class T> |
| 49 | +struct PersistentLeftistHeap { |
| 50 | + struct Node { |
| 51 | + T key; |
| 52 | + Node *left = 0, *right = 0; |
| 53 | + int dist = 0; |
| 54 | + } *root = 0; |
| 55 | + static Node *merge(Node *x, Node *y) { |
| 56 | + if (!x) return y; |
| 57 | + if (!y) return x; |
| 58 | + if (x->key > y->key) swap(x, y); |
| 59 | + x = new Node(*x); |
| 60 | + x->right = merge(x->right, y); |
| 61 | + if (!x->left || x->left->dist < x->dist) swap(x->left, x->right); |
| 62 | + x->dist = (x->right ? x->right->dist : 0) + 1; |
| 63 | + return x; |
| 64 | + } |
| 65 | + void push(T key) { root = merge(root, new Node({key})); } |
| 66 | + void pop() { root = merge(root->left, root->right); } |
| 67 | + T top() { return root->key; } |
| 68 | +}; |
| 69 | + |
| 70 | +int main() { |
| 71 | + PersistentLeftistHeap<int> heap; |
| 72 | + heap.push(3); |
| 73 | + heap.push(1); |
| 74 | + heap.push(4); |
| 75 | + heap.push(1); |
| 76 | + heap.push(5); |
| 77 | + cout << heap.top() << endl; heap.pop(); |
| 78 | + cout << heap.top() << endl; heap.pop(); |
| 79 | + auto temp = heap; |
| 80 | + cout << heap.top() << endl; heap.pop(); |
| 81 | + cout << heap.top() << endl; heap.pop(); |
| 82 | + cout << temp.top() << endl; temp.pop(); |
| 83 | + cout << temp.top() << endl; temp.pop(); |
| 84 | +} |
0 commit comments