Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions TestWorks/Test2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
class NodeHeap:
def __init__(self, key, value):
self.priority = key
self.value = value
self.degree = 0 # колво детей узлов
self.parent = None
self.child = None # left
self.sibling = None # right


class Heap:
def __init__(self):
self.head = None

def is_empty(self):
return self.head is None

def insert(self, key, value):
new_heap = Heap()
new_node = NodeHeap(key, value)
new_heap.head = new_node
self.merge(new_heap)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В merge возвращается результат, но не обновляется текущая куча, из-за этого, и того что insert игнорирует то, что возвращает merge, вставка новых элементов не будет работать.


return new_node

def get_minimum(self):
if not self.head:
return None
min_node = self.head
cur = self.head.sibling
while cur:
if cur.key < min_node.key:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У Вас в NodeHeap не было поля key

min_node = cur
cur = cur.sibling

return min_node.key

def merge(self, other_head):
if not self:
return other_head
if not other_head:
return self
result = None
curr = None
p1 = self
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Должно быть p1 = self.head, сейчас всё упадет

p2 = other_head
if p1.degree <= p2.degree:
result = p1
p1 = p1.sibling
else:
result = p2
p2 = p2.sibling
curr = result
while p1 and p2:
if p1.degree <= p2.degree:
curr.sibling = p1
p1 = p1.sibling
else:
curr.sibling = p2
p2 = p2.sibling
curr = curr.sibling
if p1:
curr.sibling = p1
else:
curr.sibling = p2
Comment on lines +54 to +65
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не выполняет merge для двух куч. Нам нужно проходить по списку и объединять деревья одинаковой степени (если есть два дерева степени k, одно становится сыном другого, получается дерево степени k+1).
В алгоритме на вики за это отвечает эта часть кода

curH = H.head                     // объединение деревьев одной степени 
while curH.sibling != null 
   if curH.degree == curH.sibling.degree
       p[curH] = curH.sibling
       tmp = curH.sibling
       curH.sibling = curH.sibling.child
       curH = tmp
       continue
   curH = curH.sibling


return result