-
Notifications
You must be signed in to change notification settings - Fork 107
/
heap.se
66 lines (56 loc) · 1.4 KB
/
heap.se
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
# min heap
data owner
data size
data elements[2^256]
def init():
self.owner = msg.sender
def push(item):
if self.owner != msg.sender:
stop
sz = self.size
self.elements[sz + 1] = item
k = sz + 1
while k > 1:
bottom = self.elements[k]
top = self.elements[k/2]
if bottom < top:
self.elements[k] = top
self.elements[k/2] = bottom
k /= 2
else:
k = 0
self.size = sz + 1
def pop():
if self.owner != msg.sender:
stop
sz = self.size
if !sz:
return(0)
prevtop = self.elements[1]
self.elements[1] = self.elements[sz]
self.elements[sz] = 0
top = self.elements[1]
k = 1
while k * 2 < sz:
bottom1 = self.elements[k * 2]
bottom2 = self.elements[k * 2 + 1]
if bottom1 < top and (bottom1 < bottom2 or k * 2 + 1 >= sz):
self.elements[k] = bottom1
self.elements[k * 2] = top
k = k * 2
elif bottom2 < top and bottom2 < bottom1 and k * 2 + 1 < sz:
self.elements[k] = bottom2
self.elements[k * 2 + 1] = top
k = k * 2 + 1
else:
k = sz
self.size = sz - 1
return(prevtop)
def top():
return(self.elements[1])
def size():
return(self.size)
def set_owner(new_owner):
if self.owner != msg.sender:
stop
self.owner = new_owner