配对堆(Pairing Heap

简介: 配对堆(Pairing Heap)是一种优先队列的数据结构,它的主要特点是每个节点都有两个子节点,分别称为左子节点和右子节点。配对堆中每个节点的优先级都大于等于(或小于等于)其子节点的优先级。它具有以下基本操作:插入、删除、查找最小值、更新最小值和堆化。

配对堆(Pairing Heap)是一种优先队列的数据结构,它的主要特点是每个节点都有两个子节点,分别称为左子节点和右子节点。配对堆中每个节点的优先级都大于等于(或小于等于)其子节点的优先级。它具有以下基本操作:插入、删除、查找最小值、更新最小值和堆化。

使用配对堆时,可以根据需要选择插入、删除或查找最小值等操作。当需要频繁插入和删除数据时,可以使用配对堆。它适用于实时数据处理、缓存和优化问题等场景。

以下是一个使用 Python 实现配对堆的简单示例:

class PairingHeap:
def init(self):
self.heap = []
def insert(self, value):
self.heap.append(value)
self._bubble_up(len(self.heap) - 1)
def delete_min(self):
if not self.heap:
return None
if len(self.heap) == 1:
return self.heap.pop()
min_value = self.heap[1]
self.heap[1] = self.heap.pop()
self._bubble_down(1)
return min_value
def find_min(self):
if not self.heap:
return None
return self.heap[1]
def update_min(self, new_value):
if not self.heap or new_value < self.heap[1]:
self.heap[1] = new_value
self._bubble_up(1)
def _bubble_up(self, index):
while index > 0:
parent_index = (index - 1) // 2
if self.heap[parent_index] > self.heap[index]:
self.heap[parent_index], self.heap[index] = self.heap[index], self.heap[parent_index]
index = parent_index
else:
break
def _bubble_down(self, index):
while 2 index + 1 < len(self.heap):
min_child_index = self._find_min_child_index(index)
if self.heap[index] > self.heap[min_child_index]:
self.heap[index], self.heap[min_child_index] = self.heap[min_child_index], self.heap[index]
index = min_child_index
else:
break
def _find_min_child_index(self, index):
left_child_index = 2
index + 1
right_child_index = 2 * index + 2
if right_child_index >= len(self.heap):
return left_child_index
else:
return left_child_index if self.heap[left_child_index] < self.heap[right_child_index] else right_child_index
CopyCopy

使用示例

ph = PairingHeap()
ph.insert(5)
ph.insert(3)
ph.insert(8)
ph.insert(1)
print(ph.find_min()) # 输出 1
print(ph.delete_min()) # 输出 1
print(ph.find_min()) # 输出 3
ph.update_min(2)
print(ph.find_min()) # 输出 2
CopyCopy

这个示例中,我们创建了一个名为 PairingHeap 的类,实现了插入、删除最小值、查找最小值和更新最小值等操作。可以根据需要使用这些方法来处理配对堆。

目录
相关文章
|
10月前
堆的介绍与堆的实现和调整
堆的介绍与堆的实现和调整
57 0
|
2月前
|
存储 算法
运用堆结构来解决Top-K问题
运用堆结构来解决Top-K问题
23 4
|
2月前
|
存储 人工智能 程序员
技术心得记录:堆(heap)与栈(stack)的区别
技术心得记录:堆(heap)与栈(stack)的区别
21 0
|
3月前
|
存储 算法 分布式数据库
【数据结构】堆(Heap)
【数据结构】堆(Heap)
|
11月前
|
存储 算法 Java
JVM系列(3):堆(Heap)
Java堆(Java Heap)是Java虚拟机所管理的内存中最大的一块。Java堆是被所有线程共享的一块内存区域,在虚拟机启动时创建。此内存区域的唯一目的就是存放对象实例,几乎所有的对象实例都在这里分配内存。Java堆是垃圾收集器管理的主要区域,因此很多时候也被称做“GC堆”。
51 0
|
3月前
|
存储 Java 程序员
堆栈与堆(Stack vs Heap)有什么区别?
堆栈与堆(Stack vs Heap)有什么区别?
42 0
|
9月前
|
Python
配对堆(Pairing Heap
配对堆(Pairing Heap)是一种基于二叉堆的可并堆数据结构,它的主要特点是每个节点都有两个子节点,分别称为左子节点和右子节点。配对堆支持插入、查询最小值、合并和修改元素等操作。它具有速度快和结构简单的优势,但由于其为基于势能分析的均摊复杂度,无法可持久化。
88 0
|
10月前
|
存储 资源调度 调度
配对堆(Pairing heap
配对堆(Pairing heap)是一种优先队列的数据结构,它的主要特点是每个节点可以有一个优先级,元素的优先级可以是任意的,可以是整数、浮点数或其他类型。配对堆支持插入、删除最小元素(即弹出最小元素)、查找最小元素以及调整优先级等操作。它具有堆的性质,即任意节点的优先级大于等于(或小于等于)其子节点优先级。
86 0
|
算法
每天一点算法-堆(Day9)
每天一点算法-堆(Day9)
52 0