-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathFibonacciHeap.cs
338 lines (264 loc) · 9.26 KB
/
FibonacciHeap.cs
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.DataStructures;
/// <summary>
/// A fibornacci minMax heap implementation.
/// </summary>
public class FibonacciHeap<T> : IEnumerable<T> where T : IComparable
{
private readonly IComparer<T> comparer;
private readonly bool isMaxHeap;
private FibonacciHeapNode<T> heapForestHead;
private readonly Dictionary<T, List<FibonacciHeapNode<T>>> heapMapping = new();
//holds the min/max node at any given time
private FibonacciHeapNode<T> minMaxNode;
public FibonacciHeap(SortDirection sortDirection = SortDirection.Ascending)
{
isMaxHeap = sortDirection == SortDirection.Descending;
comparer = new CustomComparer<T>(sortDirection, Comparer<T>.Default);
}
public int Count { get; private set; }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return heapMapping.SelectMany(x => x.Value).Select(x => x.Value).GetEnumerator();
}
/// <summary>
/// Time complexity: O(1).
/// </summary>
public void Insert(T newItem)
{
var newNode = new FibonacciHeapNode<T>(newItem);
//return pointer to new Node
MergeForests(newNode);
if (minMaxNode == null)
{
minMaxNode = newNode;
}
else
{
if (comparer.Compare(minMaxNode.Value, newNode.Value) > 0) minMaxNode = newNode;
}
AddMapping(newItem, newNode);
Count++;
}
/// <summary>
/// Time complexity: O(log(n)).
/// </summary>
public T Extract()
{
if (heapForestHead == null) throw new Exception("Empty heap");
var minMaxValue = minMaxNode.Value;
RemoveMapping(minMaxValue, minMaxNode);
//remove tree root
DeleteNode(ref heapForestHead, minMaxNode);
MergeForests(minMaxNode.ChildrenHead);
Meld();
Count--;
return minMaxValue;
}
/// <summary>
/// Update the Heap with new value for this node pointer.
/// Time complexity: O(1).
/// </summary>
public void UpdateKey(T currentValue, T newValue)
{
var node = heapMapping[currentValue]?.Where(x => x.Value.Equals(currentValue)).FirstOrDefault();
if (node == null) throw new Exception("Current value is not present in this heap.");
if (comparer.Compare(newValue, node.Value) > 0)
throw new Exception($"New value is not {(!isMaxHeap ? "less" : "greater")} than old value.");
UpdateNodeValue(currentValue, newValue, node);
if (node.Parent == null
&& comparer.Compare(minMaxNode.Value, node.Value) > 0)
minMaxNode = node;
var current = node;
if (current.Parent == null || comparer.Compare(current.Value, current.Parent.Value) >= 0) return;
var parent = current.Parent;
//if parent already lost one child
//then cut current and parent
if (parent.LostChild)
{
parent.LostChild = false;
var grandParent = parent.Parent;
//mark grand parent
if (grandParent == null) return;
Cut(parent);
Cut(current);
}
else
{
Cut(current);
}
}
/// <summary>
/// Unions this heap with another.
/// Time complexity: O(1).
/// </summary>
public void Merge(FibonacciHeap<T> fibonacciHeap)
{
MergeForests(fibonacciHeap.heapForestHead);
Count = Count + fibonacciHeap.Count;
}
/// <summary>
/// Time complexity: O(1).
/// </summary>
public T Peek()
{
if (heapForestHead == null) throw new Exception("Empty heap");
return minMaxNode.Value;
}
/// <summary>
/// Merge roots with same degrees in Forest.
/// </summary>
private void Meld()
{
if (heapForestHead == null)
{
minMaxNode = null;
return;
}
//degree - node dictionary
var mergeDictionary = new Dictionary<int, FibonacciHeapNode<T>>();
var current = heapForestHead;
minMaxNode = current;
while (current != null)
{
current.Parent = null;
var next = current.Next;
//no same degree already in merge dictionary
//add to hash table
if (!mergeDictionary.ContainsKey(current.Degree))
{
mergeDictionary.Add(current.Degree, current);
if (minMaxNode == current) minMaxNode = null;
DeleteNode(ref heapForestHead, current);
current = next;
}
//insert back to forest by merging current tree
//with existing tree in merge dictionary
else
{
var currentDegree = current.Degree;
var existing = mergeDictionary[currentDegree];
if (comparer.Compare(existing.Value, current.Value) < 0)
{
current.Parent = existing;
DeleteNode(ref heapForestHead, current);
var childHead = existing.ChildrenHead;
InsertNode(ref childHead, current);
existing.ChildrenHead = childHead;
existing.Degree++;
InsertNode(ref heapForestHead, existing);
current = existing;
current.Next = next;
}
else
{
existing.Parent = current;
var childHead = current.ChildrenHead;
InsertNode(ref childHead, existing);
current.ChildrenHead = childHead;
current.Degree++;
}
if (minMaxNode == null
|| comparer.Compare(minMaxNode.Value, current.Value) > 0)
minMaxNode = current;
mergeDictionary.Remove(currentDegree);
}
}
//insert back trees with unique degrees to forest
if (mergeDictionary.Count > 0)
{
foreach (var node in mergeDictionary)
{
InsertNode(ref heapForestHead, node.Value);
if (minMaxNode == null
|| comparer.Compare(minMaxNode.Value, node.Value.Value) > 0)
minMaxNode = node.Value;
}
mergeDictionary.Clear();
}
}
/// <summary>
/// Delete this node from Heap Tree and adds it to forest as a new tree
/// </summary>
private void Cut(FibonacciHeapNode<T> node)
{
var parent = node.Parent;
//cut child and attach to heap Forest
//and mark parent for lost child
var childHead = node.Parent.ChildrenHead;
DeleteNode(ref childHead, node);
node.Parent.ChildrenHead = childHead;
node.Parent.Degree--;
if (parent.Parent != null) parent.LostChild = true;
node.LostChild = false;
node.Parent = null;
InsertNode(ref heapForestHead, node);
//update
if (comparer.Compare(minMaxNode.Value, node.Value) > 0) minMaxNode = node;
}
/// <summary>
/// Merges the given fibornacci node list to current Forest
/// </summary>
private void MergeForests(FibonacciHeapNode<T> headPointer)
{
var current = headPointer;
while (current != null)
{
var next = current.Next;
InsertNode(ref heapForestHead, current);
current = next;
}
}
private void InsertNode(ref FibonacciHeapNode<T> head, FibonacciHeapNode<T> newNode)
{
newNode.Next = newNode.Previous = null;
if (head == null)
{
head = newNode;
return;
}
head.Previous = newNode;
newNode.Next = head;
head = newNode;
}
private void DeleteNode(ref FibonacciHeapNode<T> heapForestHead, FibonacciHeapNode<T> deletionNode)
{
if (deletionNode == heapForestHead)
{
if (deletionNode.Next != null) deletionNode.Next.Previous = null;
heapForestHead = deletionNode.Next;
deletionNode.Next = null;
deletionNode.Previous = null;
return;
}
deletionNode.Previous.Next = deletionNode.Next;
if (deletionNode.Next != null) deletionNode.Next.Previous = deletionNode.Previous;
deletionNode.Next = null;
deletionNode.Previous = null;
}
private void AddMapping(T newItem, FibonacciHeapNode<T> newNode)
{
if (heapMapping.ContainsKey(newItem))
heapMapping[newItem].Add(newNode);
else
heapMapping[newItem] = new List<FibonacciHeapNode<T>>(new[] { newNode });
}
private void UpdateNodeValue(T currentValue, T newValue, FibonacciHeapNode<T> node)
{
RemoveMapping(currentValue, node);
node.Value = newValue;
AddMapping(newValue, node);
}
private void RemoveMapping(T currentValue, FibonacciHeapNode<T> node)
{
heapMapping[currentValue].Remove(node);
if (heapMapping[currentValue].Count == 0) heapMapping.Remove(currentValue);
}
}