Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita65db14

Browse files
authored
Update finding-negative-cycle-in-graph.md
Resolves 1419.
1 parent46caa5b commita65db14

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
structEdge {
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)

[8]ページ先頭

©2009-2025 Movatter.jp