Processing math: 100%
My Algorithm : kopricky アルゴリズムライブラリ

kopricky アルゴリズムライブラリ

Dijkstra

コードについての説明

非負重みの辺のみからなるグラフに対する単一始点最短経路問題(SSSP) を効率よく解くアルゴリズム.
始点からの距離が近いものから順に探索を繰り返す("始点から最も近い頂点"は優先度付きキューを用いて効率よく管理する). ここでヒープとして二分ヒープではなくフィボナッチヒープを用いると, O((m+n)logn)O(nlogn+m) になる(参考).
また二分ヒープのかわりに Radix Heap を用いた Dijkstra 法の高速化の話もある(参考).
密なグラフ(m=Θ(n2)) については優先度付きキューを使わず一番近い頂点を愚直に計算することで O(n2) で解くことができる.
正の整数の重みの辺からなる無向グラフについては単一始点最短経路問題が線形時間で解けることが知られている.
"Undirected Single-Source Shortest Paths with Positive Integer Weights in Linear Time" [Thorup 1997]

(関数)
add_edge(u,v,cost) : u から v に向かう重み cost の有向辺を追加する
solve(s) : s を始点として各頂点までの最短距離を求める

時間計算量: O((n+m)logn)

コード

  1. template<typename T> class Dijkstra {
  2. private:
  3. struct edge{
  4. int to; T cost;
  5. };
  6. int V;
  7. vector<vector<edge> > G;
  8. vector<T> d;
  9. using pti = pair<T,int>;
  10.  
  11. public:
  12. Dijkstra(int node_size) : V(node_size), G(V), d(V, numeric_limits<T>::max()){}
  13. void add_edge(int u,int v,T cost){
  14. G[u].push_back((edge){v,cost});
  15. }
  16. void solve(int s){
  17. priority_queue<pti,vector<pti>,greater<pti> > que;
  18. d[s] = 0;
  19. que.push(pti(0,s));
  20. while(!que.empty()){
  21. pti p = que.top();
  22. que.pop();
  23. int v = p.second;
  24. if(d[v] < p.first) continue;
  25. for(auto& w : G[v]){
  26. if(d[w.to] > d[v] + w.cost){
  27. d[w.to] = d[v] + w.cost;
  28. que.push(pti(d[w.to],w.to));
  29. }
  30. }
  31. }
  32. }
  33. };

verify 用の問題

AOJ : Single Source Shortest Path 提出コード