贝尔曼福特优化

时间:2018-11-26 18:02:20

标签: c++ algorithm

下面的大家好是Bellman ford算法的实现,因为我们知道在循环(for (int i = 1; i <= V - 1; i++)的v-1(最大值)中,所有边缘将完全松弛 但是当我要在下面提到检测负体重周期时, 循环运行E

  

我认为不需要运行E次,因为如果在第一次迭代中我们发现距离仍在最小化,我们可以说存在负边缘周期,并且如果距离在第一次迭代中没有变化那么其余的E-1迭代就不会改变   如果我错了请指正我   甚至我们也可以优化发生时间弛豫的次数,如果在任何迭代中获得相同的最小距离,我们都可以退出循环

    // The main function that finds shortest distances from src to 
    // all other vertices using Bellman-Ford algorithm.  The function 
    // also detects negative weight cycle 
    void BellmanFord(struct Graph* graph, int src)
    {
        int V = graph->V;
        int E = graph->E;
        int dist[V];

        // Step 1: Initialize distances from src to all other vertices 
        // as INFINITE 
        for (int i = 0; i < V; i++)
            dist[i] = INT_MAX;
        dist[src] = 0;

        // Step 2: Relax all edges |V| - 1 times. A simple shortest  
        // path from src to any other vertex can have at-most |V| - 1  
        // edges 
        for (int i = 1; i <= V - 1; i++)
        {
            for (int j = 0; j < E; j++)
            {
                int u = graph->edge[j].src;
                int v = graph->edge[j].dest;
                int weight = graph->edge[j].weight;
                if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
                    dist[v] = dist[u] + weight;
            }
        }

        // Step 3: check for negative-weight cycles.  The above step  
        // guarantees shortest distances if graph doesn't contain  
        // negative weight cycle.  If we get a shorter path, then there 
        // is a cycle. 
        for (int i = 0; i < E; i++)
        {
            int u = graph->edge[i].src;
            int v = graph->edge[i].dest;
            int weight = graph->edge[i].weight;
            if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
                printf("Graph contains negative weight cycle");
        }

        printArr(dist, V);

        return;
    }

0 个答案:

没有答案