Skip to content

Commit 4685762

Browse files
authored
Merge pull request #1449 from cp-algorithms/mhayter-patch-3
Update finding-negative-cycle-in-graph.md
2 parents 8b37b46 + a6d8e07 commit 4685762

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

src/graph/finding-negative-cycle-in-graph.md

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30,50 +30,47 @@ Do $N$ iterations of Bellman-Ford algorithm. If there were no changes on the las
3030
struct Edge {
3131
int a, b, cost;
3232
};
33-
34-
int n, m;
33+
34+
int n;
3535
vector<Edge> edges;
3636
const int INF = 1000000000;
37-
37+
3838
void solve() {
39-
vector<int> d(n, INF);
39+
vector<int> d(n, 0);
4040
vector<int> p(n, -1);
4141
int x;
42-
43-
d[0] = 0;
44-
42+
4543
for (int i = 0; i < n; ++i) {
4644
x = -1;
4745
for (Edge e : edges) {
48-
if (d[e.a] < INF && d[e.a] + e.cost < d[e.b]) {
46+
if (d[e.a] + e.cost < d[e.b]) {
4947
d[e.b] = max(-INF, d[e.a] + e.cost);
5048
p[e.b] = e.a;
5149
x = e.b;
5250
}
5351
}
5452
}
55-
53+
5654
if (x == -1) {
5755
cout << "No negative cycle found.";
5856
} else {
5957
for (int i = 0; i < n; ++i)
6058
x = p[x];
61-
59+
6260
vector<int> cycle;
6361
for (int v = x;; v = p[v]) {
6462
cycle.push_back(v);
6563
if (v == x && cycle.size() > 1)
6664
break;
6765
}
6866
reverse(cycle.begin(), cycle.end());
69-
67+
7068
cout << "Negative cycle: ";
7169
for (int v : cycle)
7270
cout << v << ' ';
7371
cout << endl;
7472
}
7573
}
76-
7774
```
7875

7976
## Using Floyd-Warshall algorithm

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy