/*9-10(b)-12-13-20.26.c -- 第九章第十題(b)*/<br />#include <stdio.h><br />#include <stdlib.h><br />#include "binary_heap.h"</p><p>int main (void) ;<br />int new_dijkstra (const Adjacenty_List * padj, const Hash_Table * const pht, const int start) ;</p><p>int main (void)<br />{<br />Adjacenty_List adj ;<br />Hash_Table ht ;<br />int capacity = 5 ;</p><p>Initialize_H (&ht, capacity * 2) ;<br />Initialize_A (&adj, capacity) ;</p><p>InitializeALine_A (&adj, &ht, 0, 's', 0, 4, 'a', 2, 'd', 3) ;<br />InitializeALine_A (&adj, &ht, 1, 'a', 0, 2, 'b', 2) ;<br />InitializeALine_A (&adj, &ht, 2, 'b', 0, 2, 'c', 2) ;<br />InitializeALine_A (&adj, &ht, 3, 'c', 0, 2, 'd', 2) ;<br />InitializeALine_A (&adj, &ht, 4, 'd', 0, 2, 'c', 3) ;</p><p>new_dijkstra (&adj, &ht, 0) ;<br />PrintAdjacenty_List_A (&adj, &ht) ;</p><p>Release_H (&ht) ;<br />Release_A (&adj) ;</p><p>return 0 ;<br />}</p><p>int new_dijkstra (const Adjacenty_List * padj, const Hash_Table * const pht, const int start)<br />{<br />Binary_Heap bh ;<br />Vertex * v ;<br />Adjoin_To_Vertex * w ;<br />int capacity = (*padj) -> capacity, i, v_index, w_index ;<br />int * count ;</p><p>count = (int *) calloc (sizeof (int), capacity) ;<br />if (NULL == count)<br />return 0 ;<br />Initialize_B (&bh, capacity * 2) ;<br />(*padj) -> list[start].dist = 0 ;<br />for (i = 0; i < capacity; i++)<br />Insert_B (&bh, (*padj) -> list + i) ;<br />while (1)<br />{<br />do<br />{<br />v = DeleteMin_B (&bh) ;<br />if (NEGATIVEINFINITY == v -> dist)<br />break ;<br />}<br />while (TRUE == (*pht) -> lists[v -> hash_value].be_deleted)<br />;<br />if (NEGATIVEINFINITY == v -> dist)<br />break ;<br />(*pht) -> lists[v -> hash_value].be_deleted = TRUE ;<br />v -> known = TRUE ;<br />w = v -> adjoin_to ;<br />v_index = (*pht) -> lists[v -> hash_value].index_in_adjacenty_list ;<br />while (w)<br />{<br />w_index = (*pht) -> lists[w -> hash_value].index_in_adjacenty_list ;<br />if (FALSE == (*padj) -> list[w_index].known)<br />{<br />if (v -> dist + w -> cvw < (*padj) -> list[w_index].dist)<br />{<br />count[w_index] = count[v_index] + 1 ;<br />(*padj) -> list[w_index].dist = v -> dist + w -> cvw ;<br />Insert_B (&bh, (*padj) -> list + w_index) ;<br />(*padj) -> list[w_index].path = (*pht) -> lists[v -> hash_value].name ;<br />}<br />else if (v -> dist + w -> cvw == (*padj) -> list[w_index].dist)<br />{<br />if (count[v_index] + 1 < count[w_index])<br />{<br />count[w_index] = count[v_index] + 1 ;<br />(*padj) -> list[w_index].path = (*pht) -> lists[v -> hash_value].name ;<br />}<br />}<br />}<br />w = w -> next ;<br />}<br />}<br />free (count) ;<br />Release_B (&bh) ;</p><p>return 1 ;<br />} 這個常式,會在多條相同最短路徑中選出邊數最少的路徑.只是改變path域即可在遍曆的時候訪問到邊數少的路徑.核心的思想,就是建立一個數組,存放從出發點到當前頂點的最短路徑邊數.通過每次查看最短路徑相同的情況, 即dv + cvw = dw.時,如果 Count[v] + 1 < Count[w]時,就執行 Count[w] = Count[v] + 1, 同時 w -> path = c. 就是這樣吧,自己想出來的答案跟這個比較貼邊.希望,我能記住.或者,消化得好一些.