【问题标题】:Bellman ford performance贝尔曼福特表现
【发布时间】:2018-05-16 07:31:20
【问题描述】:
   for(int k=1; k<=Vertices-1; k++){   
        /*Every sublist has found the shortest to its adjacent vertices
        thats why starting loop from k-1 then going into every edge of a vertex
        and updating the shortest distance from it to the other.
        */
        for(int i=k-1; i<Vertices; i++){
            // Visiting every Vertex(V) and checking distance of its edges to some other vertex Vo.
            for(int j=0; j<Edges[i].size(); j++){
                int v = Edges[i].get(j).src;
                int edge = Edges[i].get(j).dest;
                int weight = Edges[i].get(j).weight;
                // if exisiting distance is not infinity and from source to that vertex the weight is less then update it
                if (dist[v]!=Integer.MAX_VALUE && dist[v]+weight<dist[edge]){
                    dist[edge]=dist[v]+weight;
                    //updating parent of destination to source.
                    parent[edge] = v;
                }
            }
        }
    }

我已经从(LinkedList)列表中实现了bellman ford,因为算法运行V-1(循环1)次并进入每个顶点(在Loop2中)它检查所有边缘(在loop3中)并更新距离目的地。我在这里很困惑,时间复杂度仍然是 O(VE) 或改变,我已经看到这项工作在 2 个循环中完成,这就是为什么,并且也会为每个经过的顶点找到最短路径,或者我必须从0开始?

【问题讨论】:

  • 考虑在这篇文章中添加更多细节,这将提高您获得高质量答案的可能性。

标签: java performance data-structures shortest-path bellman-ford


【解决方案1】:

就您检查 V 时间的所有边而言,复杂性仍然是 O(VE)。更多信息请阅读this

【讨论】:

  • 所以我应该将第二个循环设置为 0 以达到每个 V 次对吗?
  • @SajUsman 如果您要更改复杂度,总复杂度不会低于 O(VE)。假设您有 2 个循环,每个循环遍历 n,复杂度将是 O(n^2)。现在想象内部循环进行了 1,2,...n 次。计算这个总和 (1+2+...n) 将导致 n(n+1)/2 也是 O(n^2)。
  • 啊,现在我明白了,它总是会运行 n 次,因此在删除常量后,我们仍然会得到 n 倍的复杂度
猜你喜欢
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 2011-07-16
  • 1970-01-01
相关资源
最近更新 更多