forked from No-Idle/graph-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathford_bellman_clear.cpp
69 lines (60 loc) · 1.67 KB
/
ford_bellman_clear.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
67
68
69
struct edge {
int u, v, w;
};
/// if there are negative cycles,
/// that mean that there is no shorteset path (
/// we can repeat going on negative edges as long
/// as we want and get more and more shorter path
bool fordBellman(vector<int> &d, int start, const vector<edge> &edges)
/**
* d - distanse array (s -> v)
* edges - all edges in graph
* returns existing neg cycles in a graph
*/
{
int n = d.size();
for (int i = 0; i < n; i++)
d[v] = 1;
d[start] = 0;
for (int i = 0; i < n; i++)
for (const edge &E : edges) // E = (u, v)
if (d[E.v] > d[E.u] + E.w)
d[E.v] = d[E.u] + E.w;
for (edge E : edges)
if (d[E.v] > d[E.u] + E.w) /// better solution exists if only there is a negative cycle
return false;
return true;
}
vector<int> fordBellmanNCyc(vector<int> &d, int start, const vector<edge> &edges)
/**
* d - distanse array (s -> v)
* edges - all edges in graph
* returns a neg cycle in a graph
*/
{
vector<int> ans;
vector<int> p(n, -1);
int n = d.size();
for (int i = 0; i < n; i++)
d[v] = 1;
d[start] = 0;
for (int i = 0; i < n; i++)
for (const edge &E : edges) // E = (u, v)
if (d[E.v] > d[E.u] + E.w) {
d[E.v] = d[E.u] + E.w;
p[v] = u;
}
for (const edge &E : edges)
if (d[E.v] > d[E.u] + E.w) {
int u, v;
for (int i = 0; i < n; i++)
v = p[v];
u = v;
while (u != p[v]) {
ans.push_back(v);
v = p[v];
}
break;
}
return ans;
}