-
Notifications
You must be signed in to change notification settings - Fork 3
/
pairing_heap.cc
119 lines (90 loc) · 2.11 KB
/
pairing_heap.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
struct HeapNode {
int key;
HeapNode *leftChild;
HeapNode *nextSibling;
HeapNode():
leftChild(NULL), nextSibling(NULL) {}
HeapNode(int key_, HeapNode *leftChild_, HeapNode *nextSibling_):
key(key_), leftChild(leftChild_), nextSibling(nextSibling_) {}
void addChild(HeapNode *node) {
if(leftChild == NULL)
leftChild = node;
else {
node->nextSibling = leftChild;
leftChild = node;
}
}
};
bool Empty(HeapNode *node) {
return (node == NULL);
}
HeapNode *Merge(HeapNode *A, HeapNode *B) {
if(A == NULL) return B;
if(B == NULL) return A;
if(A->key < B->key) {
A->addChild(B);
return A;
}
else {
B->addChild(A);
return B;
}
return NULL; // Unreachable
}
int Top(HeapNode *node) {
return node->key;
}
HeapNode *Push(HeapNode *node, int key) {
return Merge(node, new HeapNode(key, NULL, NULL));
}
HeapNode *TwoPassMerge(HeapNode *node) {
if(node == NULL || node->nextSibling == NULL)
return node;
else {
HeapNode *A, *B, *newNode;
A = node;
B = node->nextSibling;
newNode = node->nextSibling->nextSibling;
A->nextSibling = NULL;
B->nextSibling = NULL;
return Merge(Merge(A, B), TwoPassMerge(newNode));
}
return NULL; // Unreachable
}
HeapNode *Pop(HeapNode *node) {
return TwoPassMerge(node->leftChild);
}
struct PairingHeap {
HeapNode *root;
PairingHeap():
root(NULL) {}
bool Empty(void) {
return ::Empty(root);
}
int Top(void) {
return ::Top(root);
}
void Push(int key) {
root = ::Push(root, key);
}
void Pop(void) {
root = ::Pop(root);
}
void Join(PairingHeap other) {
root = ::Merge(root, other.root);
}
};
int main(void) {
PairingHeap heap1, heap2;
heap1.Push(4);
heap1.Push(2);
heap2.Push(5);
heap2.Push(-1);
heap1.Join(heap2);
cout << heap1.Top() << endl;
return 0;
}