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;
}



《完》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章