Bellman-Ford

 

//Bellman-Ford 算法
#include<iostream>
using namespace std;
#define MAX_SIZE 100
#define MAX_NUMBER INT_MAX/2
struct Edge {
    int u, v;      //表示有向边<u,v>
    int w;    //边的权重
};
Edge edge[MAX_SIZE];
int dis[MAX_SIZE];
int parent[MAX_SIZE];
bool Bellman_Ford(int v, int e, int s);
int main() {
    /*测试*/
    int i,v,e, s;
    cin >> v >> e;        
    for (i = 0; i<e; i++)
        cin >> edge[i].u >> edge[i].v >> edge[i].w;
    cin >> s;
    bool flag = Bellman_Ford(v, e, s);
    for (i = 0; i<v; i++)
        cout << dis[i] << " ";
    cout << endl;
    return 0;
}
void Relax(Edge edge) {
    if (dis[edge.v] > dis[edge.u] + edge.w) {
        dis[edge.v] = dis[edge.u] + edge.w;
        parent[edge.v] = edge.u;
    }
}
bool Bellman_Ford(int v,int e,int s) {
    int i,j;
    for (i = 0; i < v; i++)
        dis[i] = MAX_NUMBER;
    parent[s] = -1;           //s设置为根结点
    dis[s] = 0;
    for (i = 1; i < v; i++) {    
        for (i = 0; i < e; i++)
            Relax(edge[i]);         //对每条边做一次松弛操作  
    }
    for (i = 0; i < e; i++) {    //检验路径长度是否收敛(是否有负环存在)
        if (dis[edge[i].v]>dis[edge[i].u] + edge[i].w)
            return false;
    }
    return true;
}

 

posted @ 2016-04-12 00:05  曹孟德  阅读(300)  评论(0编辑  收藏  举报