Dijkstra算法
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstring> 4 #include <map> 5 using namespace std; 6 /*==================================================*\ 7 | Dijkstra 数组实现O (N^2 ) 8 | Dijkstra --- 数组实现( 在此基础上可直接改为STL 的Queue实现) 9 | lowcost[] --- beg 到其他点的最近距离 10 | path[] -- beg为根展开的树,记录父亲结点 11 \*==================================================*/ 12 #define INF 0x03F3F3F3F 13 //const int N; 14 map<int, int> path, vis; 15 void Dijkstra(map<int, map<int, int> > cost, map<int, int>& lowcost, int n, int beg) { 16 int i, j, min; 17 // memset(vis, 0, sizeof(vis)); 18 vis[beg] = 1; 19 for (i = 0; i < n; i++) { 20 lowcost[i] = cost[beg][i]; 21 path[i] = beg; //最大的距离 22 } 23 lowcost[beg] = 0; //起点到自身的距离肯定是0 24 path[beg] = -1; // 树根的标记 25 int pre = beg; 26 for (i = 1; i < n; i++) { 27 min = INF; 28 for (j = 0; j < n; j++) 29 // 下面的加法可能导致溢出,INF不能取太大 30 //不能有负值,否则会出问题 31 if (vis[j] == 0 && lowcost[pre] + cost[pre][j] < lowcost[j]) { 32 lowcost[j] = lowcost[pre] + cost[pre][j]; 33 path[j] = pre; 34 } 35 for (j = 0; j < n; j++) 36 if (vis[j] == 0 && lowcost[j] < min) { //选择下一个扩展的点 37 min = lowcost[j]; 38 pre = j; 39 } 40 vis[pre] = 1; 41 } 42 } 43 int main() { 44 map<int, map<int, int> > cost; 45 map<int, int> lowcost; 46 for (int i = 0; i < 4; i++) 47 for (int j = 0; j < 4; j++) { 48 if (i != j) 49 cost[i][j] = INF; 50 else 51 cost[i][j] = 0; 52 } 53 cost[0][1] = 3; 54 cost[0][2] = 1; 55 cost[0][3] = 10; 56 cost[2][1] = 1; 57 cost[2][3] = 1; 58 59 for (int i = 0; i < 4; i++) 60 vis[i]=0; 61 Dijkstra(cost,lowcost, 4,0); 62 for (int i = 0; i < 4; i++) 63 cout<<lowcost[i]<<endl; 64 return 0; 65 }