前提は負の重みエッジを持つことはできず、最小インデックスヒープでも達成されます
#include <iostream> #include <vector> #include <stack> #include " Edge.h " #include " IndexMinHeap.h " using namespace std; テンプレート <typename Graph、typename Weight> クラスDijkstra { private : Graph&G; int s; // 源の 重量 * distTo; // 距離离 ブール *印付き; // 标记 vector <Edge <Weight> *> from ; // 最短路径是谁 公共: ダイクストラ(グラフ&グラフ、INT S):G(グラフ){ この - > S = S。 distTo = new Weight [GV()]; マーク付き = 新しい ブール値[GV()]; for(int i = 0 ; i <GV(); i ++ ){ distTo [i] = Weight(); marked [i] = false ; from .push_back(NULL); } IndexMinHeap <Weight> ipq(GV()); // ダイクストラ distTo [s] = Weight(); マーク[s] = true ; ipq.insert(s、distTo [s]); while(!ipq.isEmpty()) { int v = ipq.extractMinIndex(); // distTo [v]就是s到v的最短距離离 marked [v] = true ; // 松弛操作 typename Graph :: adjIterator adj(G、v); for(Edge <Weight> * e = adj.begin();! adj.end(); e = adj.next()){ int w = e-> other(v); if(!mark [w]){ if(from [w] == NULL || distTo [v] + e-> wt()< distTo [w]){ distTo [w] = distTo [v] + e-> wt(); から [w] = e; if (ipq.contain(w)) ipq.change(w、distTo [w]) else ipq.insert(w、distTo [w]); } } } } }; 〜ダイクストラ(){ 削除[] distTo。 マーク[]を削除; }; 重みshortestPathTo(intw){ distTo [w]を返す; } bool hasPathTo(int w){ return mark [w]; } void shortestPath(int w、vector <Edge <Weight >>&vec){ stack <Edge <Weight> *> s; Edge <Weight> * e = from [w]; while(e-> v()!= e-> w()) { s.push(e); E = から [E-> V()]。 } while(!s.empty()) { e =やめる(); vec.push_back( * e); s.pop(); } void showPath(int w){ assert(w > 0 && w < GV()); ベクトル <Edge <Weight >> vec; shortestPath(w、vec); for(int i = 0 ; i <vec.size(); i ++ ){ count << vec [i] .v()<< " -> " ; if(i == vec.size()- 1 ) count << vec [i] .w()<< endl; } } };