首先,prim算法的思想是,从一个起点开始,通过不断的纳入与当前生成树距离最短的且不在生成树中的点来构造最小生成树,当所有点都纳入到生成树以后,就得到了最小生成树。使用邻接表来存储图,能使得所需的空间最小。通过一个数组来存放各个点到当前生成树的最短距离,可以避免重复比较,从而提升效率。但我们所要获取的是该数组里的距离最小的那个点。如果没有进行堆优化,那从这个数组里找出最小距离的点的时间复杂度是O(n),通过堆优化,我们获取最小值的时间复杂度则为O(log2n),在图的点数目很大时,能有效的提升效率。
#include<iostream>
using namespace std;
struct VTshortest {
int Tdot; //到生成树的哪个点距离最短
int distance; //到生成树的最短距离
};
struct Adjoin {
//邻接表
int destination; //终点
int distance; //距离
Adjoin* next = NULL;
};
struct result {
int orgin;
int destination;
};
void heapify_up(VTshortest* shortest,int* heap,int* map,int location) {
//因为值减小,引起堆被破坏,所要进行的操作,值变小元素上浮
if (map[location] == 0) {
return;
}
if (shortest[heap[(map[location] - 1) / 2]].distance > shortest[heap[map[location]]].distance) {
int x = heap[(map[location] - 1) / 2];
swap(heap[(map[location] - 1) / 2], heap[map[location]]);
swap(map[location], map[x]);
heapify_up(shortest, heap, map, location);
}
}
void heapify_down(VTshortest* shortest, int* heap