-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathBellman-Ford Optimized.cpp
More file actions
95 lines (85 loc) · 1.89 KB
/
Bellman-Ford Optimized.cpp
File metadata and controls
95 lines (85 loc) · 1.89 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e5 + 4, M = 2e5 + 9, mod = 1e9 + 7, inf = 0x3f3f3f;
ll n, m;
int head[N], to[M], cost[M], nxt[M], ne;
void init(){
memset(head, -1, sizeof head);
ne = 0;
}
void addEdge(int f, int t, int c){
to[ne] = t;
cost[ne] = c;
nxt[ne] = head[f];
head[f] = ne++;
}
void addBiEdge(int a, int b, int c){
addEdge(a, b, c);
addEdge(b, a, c);
}
/// Time Complexity O(N * M), N = number of node & M = number of edges
ll dist[N];
bool inQ[N];
bool bellmanOptimized(ll src, ll dest){
memset(inQ, 0, sizeof inQ);
for(int i = 0; i < n; ++i)
dist[i] = INT_MAX;
dist[src] = 0;
/// queue that has all candidates
queue<int> q;
q.push(src);
inQ[src] = 1;
for(int i = 0; i < n; ++i){
/// Loop over all edges (of all candidates)
int s = q.size();
while(s--){
int u = q.front();
q.pop();
inQ[u] = 0;
/// Iterate neighbours
for(int e = head[u]; ~e; e = nxt[e]){
int v = to[e], c = cost[e];
if(dist[u] + c < dist[v]){
dist[v] = dist[u] + c;
if(!inQ[v]){
q.push(v);
inQ[v] = 1;
}
}
}
}
if(i == n - 1 && q.size()) return true;
if(q.empty()) break;
}
return false;
}
int main(){
cin >> n >> m;
init();
for(ll i = 0; i < m; ++i){
ll u, v, c;
cin >> u >> v >> c;
addBiEdge(u, v, c);
}
ll src, dest;
cin >> src >> dest;
if(bellmanOptimized(src, dest)){
cout << "There is a negative cycle\n";
}
else{
cout << "No negative cycles found.\n";
cout << dist[dest] << '\n';
}
}
/*
5 7
0 1 3
0 2 1
1 2 7
3 1 5
2 3 -13
1 4 100
3 4 7
0 4
*/