我正在使用堆数据结构实现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;
}
答案 0 :(得分:4)
要编写DecreaseKey,您需要优先级队列实现来维护从nodeTag
s到队列中的位置的映射。这意味着只要二进制堆数据结构调用交换或者可能选择基于指针的实现(例如,从不在内存中移动节点的配对堆)来更新此映射。
除非你有一个大而有点密集的图表,否则DecreaseKey不值得;只需多次插入一个节点,并忽略ExtractMin的重复结果。 (为了检测重复:每次我实现Dijkstra时,我都需要距离或树。在我选择的编程语言中,很容易从任一阵列中松一点,以记住每个节点是否已被访问过。)