-
Notifications
You must be signed in to change notification settings - Fork 0
/
bellman_ford.cpp
66 lines (61 loc) · 1.66 KB
/
bellman_ford.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<bits/stdc++.h>
using namespace std;
vector<vector<pair<int,int>>> adj;
vector<int> bellman_ford(int start, int n){
vector<int> dist(n,1e9);
dist[start] = 0;
bool cont = true;
for(int i=0;i<n-1;++i){
if(!cont) break;
cont = false;
for(int j=0;j<n;++j){
for(auto const &e: adj[j]){
if(dist[j] + e.second < dist[e.first]){
cont = true;
dist[e.first] = dist[j] + e.second;
}
}
}
}
cont = false;
for(int j=0;j<n;++j){
for(auto const &e: adj[j]){
if(dist[j] + e.second < dist[e.first]){
cont = true;
dist[e.first] = dist[j] + e.second;
}
}
}
if(cont)
cout << "NEGATIVE WEIGHT CYCLE DETECTED!!!!!111111\n";
return dist;
}
int main(){
int n,m;
n = 9;
m = 8;
adj.resize(n);
adj[0].emplace_back(1,2);
adj[0].emplace_back(5,2);
adj[1].emplace_back(0,2);
adj[1].emplace_back(2,2);
adj[1].emplace_back(3,2);
adj[2].emplace_back(1,2);
adj[2].emplace_back(6,3);
adj[3].emplace_back(1,2);
adj[3].emplace_back(4,1);
adj[3].emplace_back(5,2);
adj[4].emplace_back(3,1);
adj[4].emplace_back(6,1);
adj[5].emplace_back(0,2);
adj[5].emplace_back(3,2);
adj[6].emplace_back(4,1);
adj[6].emplace_back(2,3);
adj[7].emplace_back(8,2);
adj[8].emplace_back(7,2);
int start = 0;
vector<int> ret = bellman_ford(start,n);
for(int i=0;i!=(int)ret.size();++i){
ret[i] == 1e9 ? cout << "Not accessible\n" : cout << "Dist for " << i << ": " << ret[i] << '\n';
}
}