【问题标题】:Floyd-Warshall with negative loop in CFloyd-Warshall 在 C 中具有负循环
【发布时间】:2013-05-14 21:09:32
【问题描述】:

我正在使用 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

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

【问题讨论】:

  • 设置无效,不能有负循环

标签: c loops graph negative-number floyd-warshall


【解决方案1】:

来自wikipedia

因此,使用 Floyd–Warshall 算法检测负循环, 可以检查路径矩阵的对角线,以及是否存在 负数表示该图至少包含一个 负循环。[2]显然,在无向图中,负边 创建一个涉及其事件的负循环(即封闭步行) 顶点。

所以如果d[k][k] 永远小于0 你应该退出并说存在负循环。

【讨论】:

  • 是的,工作。添加了这个而不是 //Fix thenegative looping if((*distanceMatrix)[via][via]
猜你喜欢
  • 2016-01-18
  • 2015-04-26
  • 1970-01-01
  • 2013-03-20
  • 2014-05-09
  • 1970-01-01
  • 2015-01-31
  • 2012-07-07
  • 1970-01-01
相关资源
最近更新 更多