1

我正在使用堆数据结构实现 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;
}
4

1 回答 1

4

要编写 DecreaseKey,您需要优先级队列实现来维护从nodeTags 到队列中位置的映射。这意味着每当二进制堆数据结构需要交换时更新此映射,或者可能选择基于指针的实现,例如永远不会在内存中移动节点的配对堆。

除非你有一个大的、有点密集的图表,否则 DecreaseKey 是不值得的;只需多次插入一个节点并忽略来自 ExtractMin 的重复结果。(检测重复:每次我实现 Dijkstra 时,我都需要距离或树。在我选择的编程语言中,很容易从任一数组中稍微松动一下,以记住每个节点是否已被访问.)

于 2013-05-29T20:59:22.463 回答