C++算法实现Bellman-Ford算法

Bellman-Ford算法的时间复杂度为O(VE);

#include<iostream>
#include<vector>
#include<cmath>
using std::cout;
using std::endl;
using std::vector;
struct edge
{
    int from;
    int to;
    double weight;
};
struct graph
{
private:
    int V;
    vector<edge> E;
public:
    graph(int v)
        : V(v)
    {
    }
    void insert_edge(int from, int to, double weight)
    {
        edge e;
        e.from = from;
        e.to = to;
        e.weight = weight;
        E.push_back(e);
    }
    void bellman_ford(int s)
    {
        vector<double> d(V);
        for(int i=0;i<V;i++){
            d[i]=INFINITY;
        }
        d[s]=0;
        bool updated;
        for(int i=0;i<V;i++){
            updated=false;
            for(auto e:E){
                if(d[e.from]+e.weight<d[e.to]){
                    d[e.to]=d[e.from]+e.weight;
                    updated=true;
                }
                }
            if(!updated){
                    break;
            } 
        }
        if(updated){
            cout<<"There is a negative cycle."<<endl;
        }
        else{
            for(int i=0;i<V;i++){
                cout<<d[i]<<endl;
            }
        }
    }
};
int main()
{
    graph g(6);
    g.insert_edge(0, 1, 10);
    g.insert_edge(0, 2, 20);
    g.insert_edge(2, 1, -15);
    g.insert_edge(2, 4, 5);
    g.insert_edge(4, 3, -5);
    g.insert_edge(2, 3, -1);
    cout << "Before inserting (4, 2, -6):" << endl;
    g.bellman_ford(0);
    cout << "After inserting (4, 2, -6):" << endl;
    g.insert_edge(4, 2, -6);
    g.bellman_ford(0);
    return 0;
}

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/qq_36499686/article/details/78159137
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞