我在课本中使用了这个Binary Heap实现代码。但我不明白密钥构建堆的必要性。
#define MAXREAL 999999.0
class HeapItem
{
public:
int data; //actual data that is stored
float key; //key value of the data, heap is constructed based on key
};
class MinHeap
{
public:
HeapItem * A; //stores heap items, e.g., nodes
int heapLength;
int * map;
MinHeap() //constructor
{
A = new HeapItem[MAX_HEAP_SIZE];
map = new int[MAX_HEAP_SIZE];
heapLength = 0;
}
//Fills the heap with an array of integers
//key values do not maintain heap property
//May be used in some algorithms such as dijkstra's shortest path
void initialize(int v[], int n)
{
heapLength = n;
for (int i = 0; i<n; i++) //nodes are stored from index 1 instead of 0 in the heap
{
A[i + 1].data = v[i];
A[i + 1].key = MAXREAL;
map[v[i]] = i + 1; //map tracks which vertex is stored at which heap node
}
}
}
MinHeap中键和地图的功能是什么?
答案 0 :(得分:0)
在你的情况下,密钥什么都不做,它甚至出现在评论中:
//key values do not maintain heap property
//May be used in some algorithms such as dijkstra's shortest path
另请注意,所有密钥都已分配给MAXREAL
,基本上可以使用该密钥以便keep the heap property。
在您的情况下,这不能称为堆。因为没有调用Heapify
进程,并且没有对数组中的顺序进行假设。基本上它意味着您的数据集中没有特定的顺序,因此这不是最小堆。
同样在堆中,元素存储在0位置 - 这是最小值。
看起来代码不完整或不正确
答案 1 :(得分:0)