我正在使用堆数据结构实现 Dijkstra 算法。我还使用一个数组来跟踪节点的“可能的最小距离”。问题是当我更新数组时,如何更新堆中相应的值?
好的,这是代码
typedef struct temp
{
int nodeTag;
int weight;
struct temp *next;
}myStruct; //this structure corresponds to the elements of the linked list
typedef struct temp *link;
typedef struct
{
int nodeTag; //each node has an integer nodeTag associated with it
link l;
}head; //the head of the elements of the adjacency list
typedef struct {
head *adjList;
int numNodes;
int numEdges;
} Graph;
typedef struct {
int possibleMinWeight;
int minFound; //minFound==1 if true min is found
} dummy;
dummy *dijkstraSSSP(Graph G, int nodeTag)
{
minHeap H=createEmptyHeap(G.numNodes);
while(i=0;i<G.numNodes;i++)
{
if(i!=nodeTag)
H.A[i].priority=INFINITY;
else
H.A[i].priority=0;
H.A[i].nodeTag=i;
}
convertIntoHeap(H);
int min;
dummy *A=(dummy *)malloc(sizeof(int)*G.numNodes);
A[nodeTag-1].possibleMinWeight=0;
A[nodeTag-1].minFound=1;
while(!isEmpty(H))
{
element e=findMin(H); H=deleteMin(H);
A[e.nodeTag-1].minFound=1;
link l=G.adjList[e.nodeTag-1].l;
while(l!=NULL)
{
if(A[l->nodeTag-1].minFound==0); //its true minimum distance is yet to be found
{
if(A[l->nodeTag-1].possibleMinWeight>A[x-1].possibleMinWeight+(l->weight))
A[l->nodeTag-1].possibleMinWeight=A[x-1]+(l->weight);
}
l=l->next;
}
}
return A;
}
Run Code Online (Sandbox Code Playgroud)
nodeTag要编写 DecreaseKey,您需要优先级队列实现来维护从s 到队列中位置的映射。这意味着只要二进制堆数据结构需要交换或者选择基于指针的实现(例如从不移动内存中的节点的配对堆),就更新此映射。
除非你有一个大的、有点密集的图表,否则 DecreaseKey 不值得;只需多次插入一个节点并忽略 ExtractMin 的重复结果。(为了检测重复:每次我实现 Dijkstra 时,我都需要距离或树。在我选择的编程语言中,很容易从任一数组中松动一点来记住每个节点是否已被访问过.)