-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day10.py
58 lines (46 loc) · 1.63 KB
/
Day10.py
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
# a binary heap creates a complete binary tree
class BinaryHeap:
def __init__(self):
self.heap_list = [0]
self.current_size = 0
def perc_up(self, i):
while i // 2 > 0:
if self.heap_list[i] < self.heap_list[i // 2]:
tmp = self.heap_list[i // 2]
self.heap_list[i // 2] = self.heap_list[i]
self.heap_list[i] = tmp
i = i // 2
def insert(self, k):
self.heap_list.append(k)
self.current_size = self.current_size + 1
self.perc_up(self.current_size)
def perc_down(self, i):
while (i * 2) <= self.current_size:
mc = self.min_child(i)
if self.heap_list[i] > self.heap_list[mc]:
tmp = self.heap_list[i]
self.heap_list[i] = self.heap_list[mc]
self.heap_list[mc] = tmp
i = mc
def min_child(self, i):
if i * 2 + 1 > self.current_size:
return i * 2
else:
if self.heap_list[i * 2] < self.heap_list[i * 2 + 1]:
return i * 2
else:
return i * 2 + 1
def del_min(self):
ret_val = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.current_size]
self.current_size = self.current_size - 1
self.heap_list.pop()
self.perc_down(1)
return ret_val
def build_heap(self, a_list):
i = len(a_list)//2
self.current_size = len(a_list)
self.heap_list = [0] + a_list[:]
while(i>0):
self.perc_down(i)
i-=1