Loading [Contrib]/a11y/accessibility-menu.js
$\newcommand{\O}{\mathrm{O}}$ My Algorithm : kopricky アルゴリズムライブラリ

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

Bellman Ford

コードについての説明

負辺を含むグラフに対する単一始点最短経路問題(SSSP) を効率よく解くことができるアルゴリズム. また負の有向閉路の検出(3種類)も同じ計算量で行うことが可能.
全辺を見て始点からの最短距離が更新されるなら更新するという操作を $n$ 回行う. それ以降もなお最短距離が更新される場合は始点から到達可能な負の有向閉路が存在することになる.

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

時間計算量: $\O (nm)$

コード

  1. template<typename T> class bellman_ford {
  2. public:
  3. struct edge{
  4. int from, to;
  5. T cost;
  6. };
  7. int V;
  8. T inf;
  9. vector<T> d;
  10. vector<edge> es;
  11. bellman_ford(int node_size) : V(node_size), inf(numeric_limits<T>::max()/2), d(V, inf){}
  12. void add_edge(int from, int to, T cost){
  13. es.push_back((edge){from, to, cost});
  14. }
  15. //sからの最短路長およびsからたどり着ける負の閉路の検出(trueなら負の閉路が存在する)
  16. bool solve(int s){
  17. int cnt = 0;
  18. d[s] = 0;
  19. while(cnt < V){
  20. bool update = false;
  21. for(auto& e : es){
  22. if(d[e.from] != inf && d[e.to] > d[e.from] + e.cost){
  23. d[e.to] = d[e.from] + e.cost;
  24. update = true;
  25. }
  26. }
  27. if(!update) break;
  28. cnt++;
  29. }
  30. return (cnt == V);
  31. }
  32. //すべての負の閉路の検出(trueなら負の閉路が存在する)
  33. bool find_negative_loop(){
  34. fill(d.begin(), d.end(), (T)0);
  35. int cnt = 0;
  36. while(cnt < V){
  37. bool update = false;
  38. for(auto& e : es){
  39. if(d[e.to] > d[e.from] + e.cost){
  40. d[e.to] = d[e.from] + e.cost;
  41. update = true;
  42. }
  43. }
  44. if(!update) break;
  45. cnt++;
  46. }
  47. return (cnt == V);
  48. }
  49. // s, t 間の最短距離が非有界
  50. bool shortest_path_infinite(int s, int t){
  51. d[s] = 0;
  52. for(int i = 0; i < 2*V-1; i++){
  53. for(auto& e : es){
  54. if(d[e.from] != inf && d[e.to] > d[e.from] + e.cost){
  55. d[e.to] = d[e.from] + e.cost;
  56. if(i >= V-1){
  57. if(e.to == t) return true;
  58. d[e.to] = -inf;
  59. }
  60. }
  61. }
  62. }
  63. return false;
  64. }
  65. };

verify 用の問題

最短経路と始点sからたどり着ける閉路を verify
AOJ : Single Source Shortest Path (Negative Edges) 提出コード
すべての負の閉路の検出を verify
Atcoder : Asteroids2 提出コード
s, t 最短距離が非有界となるかの判定の verify
Atcoder: Coins Respawn 提出コード