Kyopro Library
 
読み取り中…
検索中…
一致する文字列を見つけられません
bellman_ford.hpp
[詳解]
1#include"../../../kyopro_library/template.hpp"
2
3/**
4 * @brief ベルマンフォード法
5 * @details 負の閉路が存在するか否かの bool 値と、各頂点までの最短距離を記録した配列の組を返す
6 * @note O(VE)
7 * @attention
8 * 負閉路が存在する場合、最短経路が正しく計算されない場合がある。
9 * このときは逆辺を張ったグラフで BFS 等を行い、目的の終点から到達可能である頂点を列挙し、
10 * そのような頂点のみでベルマンフォード法を実行して調べる必要がある。
11 * @ref https://yukicoder.me/submissions/967952
12 * @ref https://mhrb-minase.hatenablog.com/entry/2019/08/20/003915
13 */
14pair<bool,vector<ll>> BellmanFord(const vector<vector<pair<int,ll>>>& g, int start) {
15 int n=g.size();
16 vector<ll> dst(n,INFL); dst[start]=0;
17 int i=0;
18 for(; i<n; i++) {
19 bool update=false;
20 for(int j=0; j<n; j++) {
21 for(auto [nxt,cost]:g[j]) {
22 if(dst[j]!=INFL&&dst[j]+cost<dst[nxt]) {
23 dst[nxt]=dst[j]+cost;
24 update=true;
25 }
26 }
27 }
28 if(!update) break;
29 }
30 return {i==n,dst};
31}
pair< bool, vector< ll > > BellmanFord(const vector< vector< pair< int, ll > > > &g, int start)
ベルマンフォード法