我正在尝试使用Prim的Min Spanning Tree算法优化图形.但我没有得到理想的答案.
算法:
1. Construct min heap array. The array consists of nodes which have a vertex value
and a key value. The key values are initialized to INT_MAX initially.
2. Make the zeroth node's key 0, as this is the starting node.
3. I iterate over the heap, till it becomes empty, and in every step following is done:
- Extract the minimum element out of the min heap. This is done by extractMin()
function in the class MinHeap.
4. Look for this extracted element's neighbors and update their keys based on the weight of
the corresponding edge.
5. Then decrease the key value in the minHeap by using decreaseKey() function in
class MinHeap.
6. Store the parent and child for which the condition satisfies in a map called parent.
这是代码说明:
1. The code contains two header files, Graph.h and MinHeap.h. The functions are all std f
functions in these files. So there won't be any problem in understanding them.
2. The Graph.cpp file contains the PrimMST() function which does all the job and performs
the entire algorithm.
这是问题所在:
1. When I extract a node from heap in PrimMST() function, I call extractMin() function
defined in MinHeap.cpp file. This function swaps the top most node in the heap with the
bottom most node. And then performs the heapify operation.
But, it is not performing this operation though I have called it in extractMin(). There's
no problem with minHeapify function which does the heapify operation as it does
perform its job else where is the program.
这是我想要优化的图表:
这是程序:PS:我发布了包含所有头文件的整个代码,因此可以很容易地理解它.但是跳过代码并请观察Graph.cpp文件中的PrimMST()函数.
/***************GRAPH.H*******************************/
#ifndef GRAPH_H_
#define GRAPH_H_
#include
#include
有了这个输入,我得到了错误的输出.请注意,通过在调用extractMin()之前和之后调用printHeap来获取此输出.并且可以看出,即使每次提取节点时在extractMin()中调用minHeapify(0).它以某种方式不执行操作,因此堆没有堆化,导致错误的结果Sample输出,前3次迭代:
First Iteration:
0, 0
1, 2147483647
2, 2147483647
3, 2147483647
4, 2147483647
5, 2147483647
6, 2147483647
7, 2147483647
8, 2147483647
8, 2147483647
1, 2147483647
2, 2147483647
3, 2147483647
4, 2147483647
5, 2147483647
6, 2147483647
7, 214748364
Second Iteration:
1, 4
7, 8
2, 2147483647
8, 2147483647
4, 2147483647
5, 2147483647
6, 2147483647
3, 2147483647
3, 2147483647
7, 8
2, 2147483647
8, 2147483647
4, 2147483647
5, 2147483647
6, 2147483647
Third Iteration:
2, 8
7, 8
3, 2147483647
8, 2147483647
4, 2147483647
5, 2147483647
6, 2147483647
6, 2147483647
7, 8
3, 2147483647
8, 2147483647
4, 2147483647
5, 2147483647
请注意第二次和第三次迭代,这些都没有堆积,即使我最后在extractMin()函数中调用了minHeapify函数.
我迫切需要帮助.