gpt4 book ai didi

c - Floyd-Warshall 在 C 中使用负循环

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:57 25 4
gpt4 key购买 nike

我正在使用 Floyd-Warshalls 算法进行图搜索,但不了解如何更改它以防止负循环。

当我输入时:

From  Cost   To
0 -1 1
1 -2 0

我得到成本矩阵:

   0   1
0 -3 -4
1 -5 -10

然后它开始循环直到它崩溃,因为它仍然增加负边缘并进一步降低成本。

void FloydWarshall(int ***distanceMatrix, int maxVertices)
{
int from, to, via;

for(from = 0; from < maxVertices; from++)
{
for(to = 0; to < maxVertices; to++)
{
for(via = 0; via < maxVertices; via++)
{
//Fix the negative looping
//EDIT FIX:
if((*distanceMatrix)[via][via]<0)
{fprintf(stderr, "Contains negative cycle!\n"); continue;}
//END EDIT
//Searches for the cheapest way from all-to-all nodes, if new path
// is cheaper than the previous one, its updated in matrix
(*distanceMatrix)[from][to] = min((*distanceMatrix)[from][to],
((*distanceMatrix)[from][via]+(*distanceMatrix)[via][to]));
}
}
}
}

最小值在哪里:

int min(int a,int b)
{return (a<b)? a:b;}

并且我的 distanceMatrix 在任何没有成本的地方都有 INF。

我遇到了较旧的主题,其中更改后的算法是这样的:

for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++) // Go through all possible sources and targets

for(int k = 0; d[i][j] != -INF && k < n; k++)
if( d[i][k] != INF && // Is there any path from i to k?
d[k][j] != INF && // Is there any path from k to j?
d[k][k] < 0) // Is k part of a negative loop?

d[i][j] = -INF; // If all the above are true
// then the path from i to k is undefined

但是,即使我使用此修复程序而不是我的函数,它仍然会循环并进一步降低成本。此修复是否正确?如果没有,我应该如何重写它?谢谢。

最佳答案

来自 wikipedia

Hence, to detect negative cycles using the Floyd–Warshall algorithm, one can inspect the diagonal of the path matrix, and the presence of a negative number indicates that the graph contains at least one negative cycle.[2] Obviously, in an undirected graph a negative edge creates a negative cycle (i.e., a closed walk) involving its incident vertices.

因此,如果 d[k][k] 小于 0,您应该退出并说明存在负循环。

关于c - Floyd-Warshall 在 C 中使用负循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16552916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com