1. 程式人生 > >Bellman-Ford

Bellman-Ford

bellman-ford 單源最短路徑

1、對每條邊松弛|V|-1次

2、解決單源最短路徑問題

3、一般情況,變得權重可以為負

4、時間復雜度O(V*E)


偽碼:

BELLMAN-FORD(G,w,S)

INITIALIZE-SINGLE-SOURCR(G,S) 1、初始化所有節點

for i=1 to |G.V|-1 2、進行循環

for each edge(u,v)屬於G.E

RELAX(u,v,w) 對每條邊都進行一次松弛

for each edge(u,v)屬於G.E 3、判斷是否存在權值為負的回路

if v.d > u.d+w(u,v)

return FALSE

return TRUE



C++實現

typedef struct Edge{
       int src;
       int dst;
       int weight;
}Edge;
int nodenum;
int edgenum;
int source;
const int MAXINT = 9999;
const int MAXNUM = 100;
Edge edge[MAXNUM];
int dist[MAXNUM];

void init()
{
       cout << "輸入節點的個數:"; cin >> nodenum;
       cout << "輸入邊的條數:"; cin >> edgenum;
       cout << "輸入源節點的編號:"; cin >> source;
       for (int i = 1; i <= nodenum; ++i)
              dist[i] = MAXINT;
       dist[source] = 0;
       cout << "輸入" << edgenum << "行src dst weight";
       for (int i = 1; i <= edgenum; ++i){
              cin >> edge[i].src >> edge[i].dst >> edge[i].weight;
              if (edge[i].src == source){
                     dist[edge[i].dst] = edge[i].weight;
              }
       }
}
bool bellmanFord()
{
       init();
       for (int i = 1; i <= nodenum - 1; ++i){
              for (int j = 1; j <= edgenum; ++j){
                     //relax
                     int u = edge[j].src;
                     int v = edge[j].dst;
                     int weight = edge[j].weight;
                     if (dist[v] > dist[u] + weight)
                           dist[v] = dist[u] + weight;
              }
       }
       for (int i = 1; i <= edgenum; ++i){
              //判斷是否有負權重值的回路
              int u = edge[i].src;
              int v = edge[i].dst;
              int weight = edge[i].weight;
              if (dist[v] > dist[u] + weight)
                     return false;
       }
       return true;
}
int main()
{
       if (bellmanFord()){
              for (int i = 1; i <= nodenum; ++i)
                     cout << dist[i] << " ";
              cout << endl;
       }
       system("pause");
       return 0;
}



《完》

本文出自 “零蛋蛋” 博客,謝絕轉載!

Bellman-Ford