-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBellman_Ford.cpp
More file actions
69 lines (57 loc) · 1.23 KB
/
Bellman_Ford.cpp
File metadata and controls
69 lines (57 loc) · 1.23 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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
struct Edge {
int64_t u, v, w;
};
const int64_t INF = 4e18;
vector<Edge> edges;
vector<int> neg_path;
int64_t d[N], p[N];
// false -> exist negative cycle
bool bellman_ford(int s, int n) { // O(n*m)
fill(d, d + n, INF);
fill(p, p + n, -1);
neg_path.clear();
d[s] = 0;
int x = -1;
for (int i = 0; i < n; i++) {
x = -1;
for (auto &e : edges) {
if (d[e.u] < INF) {
if (d[e.v] > d[e.u] + e.w) {
d[e.v] = max(-INF, d[e.u] + e.w);
p[e.v] = e.u;
x = e.v;
}
}
}
if (x == -1) {
return false;
}
}
int y = x;
for (int i = 0; i < n; i++) {
y = p[y];
}
for (int cur = y; ; cur = p[cur]) {
neg_path.push_back(cur);
if (cur == y && int(neg_path.size()) > 1) {
break;
}
}
reverse(neg_path.begin(), neg_path.end());
return true;
}
void solve() {
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}