1. 程式人生 > 程式設計 >C++計算任意權值的單源最短路徑(Bellman-Ford)

C++計算任意權值的單源最短路徑(Bellman-Ford)

本文例項為大家分享了C++計算任意權值單源最短路徑的具體程式碼,供大家參考,具體內容如下

一、有Dijkstra演算法求最短路徑了,為什麼還要用Bellman-Ford演算法

Dijkstra演算法不適合用於帶有負權值的有向圖。

如下圖:

C++計算任意權值的單源最短路徑(Bellman-Ford)

用Dijkstra演算法求頂點0到各個頂點的最短路徑:

(1)首先,把頂點0新增到已訪問頂點集合S中,選取權值最小的鄰邊<0,2>,權值為5

記錄頂點2的最短路徑為:dist[2]=5,path[2]=0,把頂點2新增到集合S中。

頂點2,沒有鄰邊(從頂點2出發,其他頂點為終點的邊),結束;

(2)訪問<0,1>邊,權值為7,把頂點7新增到頂點集合S中,dist[1]=7,path[1]=0。

雖然,頂點1有鄰邊<1,2>,但是因為頂點2已在集合S中,所以,不繼續修改,結束程式。

所以,最終dist[1]=7,dist[2]=5。顯然結果不對,頂點2的最短路徑應為:0->1->2,權值為7+(-5)=2

二、Bellman-Ford演算法思路:

Bellman-Ford演算法,效率低,但是適合用於求帶有負權值的單源最短路徑。

不考慮有迴路的,如下圖,頂點0到頂點1的最短路徑可以無窮小

C++計算任意權值的單源最短路徑(Bellman-Ford)

下面開始簡單描述Bellman-Ford的思路:

C++計算任意權值的單源最短路徑(Bellman-Ford)C++計算任意權值的單源最短路徑(Bellman-Ford)

C++計算任意權值的單源最短路徑(Bellman-Ford)

可以,看到:通過繞過一些頂點,可以取得更短的路徑長度

當k=1時,即從源點(頂點0)到其他頂點,只需要一條邊。有<0,1>、<0,2>、<0,3>,所以有:dist[1]=6,dist[2]=5,dist[3]=5;

當k=2時,需要2條邊的,u=1,有0->2->3,長度為:5+(-2)=3, 更短,所以要修改dist[1]=3;

u=2,有:0->3->2,長度為:5+(-2)=3,更短,所以要修改dist[2]=3;

u=3,沒有兩條邊從頂點0到達頂點3的路徑;

u=4,有0->1->4,長度為:6+(-1)=5, 更短,所以要修改dist[4]=5;

u=5,有0->3->5,長度為:5+(-1)=4,更短,所以要修改dist[5]=4;

u=6,沒有2條邊就可以從頂點0到頂點6的路徑。

重複上面步驟,直到k=n-1結束程式。

C++計算任意權值的單源最短路徑(Bellman-Ford)

三、實現程式:

1.Graph.h:有向圖

#ifndef Graph_h
#define Graph_h
 
#include <iostream>
using namespace std;
 
const int DefaultVertices = 30;
 
template <class T,class E>
struct Edge { // 邊結點的定義
  int dest; // 邊的另一頂點位置
  E cost; // 表上的權值
  Edge<T,E> *link; // 下一條邊鏈指標
};
 
template <class T,class E>
struct Vertex { // 頂點的定義
  T data; // 頂點的名字
  Edge<T,E> *adj; // 邊連結串列的頭指標
};
 
template <class T,class E>
class Graphlnk {
public:
  const E maxValue = 100000; // 代表無窮大的值(=∞)
  Graphlnk(int sz=DefaultVertices); // 建構函式
  ~Graphlnk(); // 解構函式
  void inputGraph(); // 建立鄰接表表示的圖
  void outputGraph(); // 輸出圖中的所有頂點和邊資訊
  T getValue(int i); // 取位置為i的頂點中的值
  E getWeight(int v1,int v2); // 返回邊(v1, v2)上的權值
  bool insertVertex(const T& vertex); // 插入頂點
  bool insertEdge(int v1,int v2,E weight); // 插入邊
  bool removeVertex(int v); // 刪除頂點
  bool removeEdge(int v1,int v2); // 刪除邊
  int getFirstNeighbor(int v); // 取頂點v的第一個鄰接頂點
  int getNextNeighbor(int v,int w); // 取頂點v的鄰接頂點w的下一鄰接頂點
  int getVertexPos(const T vertex); // 給出頂點vertex在圖中的位置
  int numberOfVertices(); // 當前頂點數
private:
  int maxVertices; // 圖中最大的頂點數
  int numEdges; // 當前邊數
  int numVertices; // 當前頂點數
  Vertex<T,E> * nodeTable; // 頂點表(各邊連結串列的頭結點)
};
 
// 建構函式:建立一個空的鄰接表
template <class T,class E>
Graphlnk<T,E>::Graphlnk(int sz) {
  maxVertices = sz;
  numVertices = 0;
  numEdges = 0;
  nodeTable = new Vertex<T,E>[maxVertices]; // 建立頂點表陣列
  if(nodeTable == NULL) {
    cerr << "儲存空間分配錯誤!" << endl;
    exit(1);
  }
  for(int i = 0; i < maxVertices; i++)
    nodeTable[i].adj = NULL;
}
 
// 解構函式
template <class T,E>::~Graphlnk() {
  // 刪除各邊連結串列中的結點
  for(int i = 0; i < numVertices; i++) {
    Edge<T,E> *p = nodeTable[i].adj; // 找到其對應連結串列的首結點
    while(p != NULL) { // 不斷地刪除第一個結點
      nodeTable[i].adj = p->link;
      delete p;
      p = nodeTable[i].adj;
    }
  }
  delete []nodeTable; // 刪除頂點表陣列
}
 
// 建立鄰接表表示的圖
template <class T,class E>
void Graphlnk<T,E>::inputGraph() {
  int n,m; // 儲存頂點樹和邊數
  int i,j,k;
  T e1,e2; // 頂點
  E weight; // 邊的權值
  
  cout << "請輸入頂點數和邊數:" << endl;
  cin >> n >> m;
  cout << "請輸入各頂點:" << endl;
  for(i = 0; i < n; i++) {
    cin >> e1;
    insertVertex(e1); // 插入頂點
  }
  
  cout << "請輸入圖的各邊的資訊:" << endl;
  i = 0;
  while(i < m) {
    cin >> e1 >> e2 >> weight;
    j = getVertexPos(e1);
    k = getVertexPos(e2);
    if(j == -1 || k == -1)
      cout << "邊兩端點資訊有誤,請重新輸入!" << endl;
    else {
      insertEdge(j,k,weight); // 插入邊
      i++;
    }
  } // while
}
 
// 輸出有向圖中的所有頂點和邊資訊
template <class T,E>::outputGraph() {
  int n,m,i;
  T e1,e2; // 頂點
  E weight; // 權值
  Edge<T,E> *p;
  
  n = numVertices;
  m = numEdges;
  cout << "圖中的頂點數為" << n << ",邊數為" << m << endl;
  for(i = 0; i < n; i++) {
    p = nodeTable[i].adj;
    while(p != NULL) {
      e1 = getValue(i); // 有向邊<i,p->dest>
      e2 = getValue(p->dest);
      weight = p->cost;
      cout << "<" << e1 << "," << e2 << "," << weight << ">" << endl;
      p = p->link; // 指向下一個鄰接頂點
    }
  }
}
 
// 取位置為i的頂點中的值
template <class T,class E>
T Graphlnk<T,E>::getValue(int i) {
  if(i >= 0 && i < numVertices)
    return nodeTable[i].data;
  return NULL;
}
 
// 返回邊(v1, v2)上的權值
template <class T,class E>
E Graphlnk<T,E>::getWeight(int v1,int v2) {
  if(v1 != -1 && v2 != -1) {
    if(v1 == v2) // 說明是同一頂點
      return 0;
    Edge<T,E> *p = nodeTable[v1].adj; // v1的第一條關聯的邊
    while(p != NULL && p->dest != v2) { // 尋找鄰接頂點v2
      p = p->link;
    }
    if(p != NULL)
      return p->cost;
  }
  return maxValue; // 邊(v1,v2)不存在,就存放無窮大的值
}
 
// 插入頂點
template <class T,class E>
bool Graphlnk<T,E>::insertVertex(const T& vertex) {
  if(numVertices == maxVertices) // 頂點表滿,不能插入
    return false;
  nodeTable[numVertices].data = vertex; // 插入在表的最後
  numVertices++;
  return true;
}
 
// 插入邊
template <class T,E>::insertEdge(int v1,E weight) {
  if(v1 == v2) // 同一頂點不插入
    return false;
  if(v1 >= 0 && v1 < numVertices && v2 >= 0 && v2 < numVertices) {
    Edge<T,E> *p = nodeTable[v1].adj; // v1對應的邊連結串列頭指標
    while(p != NULL && p->dest != v2) // 尋找鄰接頂點v2
      p = p->link;
    if(p != NULL) // 已存在該邊,不插入
      return false;
    p = new Edge<T,E>; // 建立新結點
    p->dest = v2;
    p->cost = weight;
    p->link = nodeTable[v1].adj; // 鏈入v1邊連結串列
    nodeTable[v1].adj = p;
    numEdges++;
    return true;
  }
  return false;
}
 
// 有向圖刪除頂點較麻煩
template <class T,E>::removeVertex(int v) {
  if(numVertices == 1 || v < 0 || v > numVertices)
    return false; // 表空或頂點號超出範圍
  
  Edge<T,E> *p,*s;
  // 1.清除頂點v的邊連結串列結點w 邊<v,w>
  while(nodeTable[v].adj != NULL) {
    p = nodeTable[v].adj;
    nodeTable[v].adj = p->link;
    delete p;
    numEdges--; // 與頂點v相關聯的邊數減1
  } // while結束
  // 2.清除<w,v>,與v有關的邊
  for(int i = 0; i < numVertices; i++) {
    if(i != v) { // 不是當前頂點v
      s = NULL;
      p = nodeTable[i].adj;
      while(p != NULL && p->dest != v) {// 在頂點i的連結串列中找v的頂點
        s = p;
        p = p->link; // 往後找
      }
      if(p != NULL) { // 找到了v的結點
        if(s == NULL) { // 說明p是nodeTable[i].adj
          nodeTable[i].adj = p->link;
        } else {
          s->link = p->link; // 儲存p的下一個頂點資訊
        }
        delete p; // 刪除結點p
        numEdges--; // 與頂點v相關聯的邊數減1
      }
    }
  }
  numVertices--; // 圖的頂點個數減1
  nodeTable[v].data = nodeTable[numVertices].data; // 填補,此時numVertices,比原來numVertices小1,所以,這裡不需要numVertices-1
  nodeTable[v].adj = nodeTable[numVertices].adj;
  // 3.要將填補的頂點對應的位置改寫
  for(int i = 0; i < numVertices; i++) {
    p = nodeTable[i].adj;
    while(p != NULL && p->dest != numVertices) // 在頂點i的連結串列中找numVertices的頂點
      p = p->link; // 往後找
    if(p != NULL) // 找到了numVertices的結點
      p->dest = v; // 將鄰接頂點numVertices改成v
  }
  return true;
}
 
// 刪除邊
template <class T,E>::removeEdge(int v1,int v2) {
  if(v1 != -1 && v2 != -1) {
    Edge<T,E> * p = nodeTable[v1].adj,*q = NULL;
    while(p != NULL && p->dest != v2) { // v1對應邊連結串列中找被刪除邊
      q = p;
      p = p->link;
    }
    if(p != NULL) { // 找到被刪除邊結點
      if(q == NULL) // 刪除的結點是邊連結串列的首結點
        nodeTable[v1].adj = p->link;
      else
        q->link = p->link; // 不是,重新連結
      delete p;
      return true;
    }
  }
  return false; // 沒有找到結點
}
 
// 取頂點v的第一個鄰接頂點
template <class T,class E>
int Graphlnk<T,E>::getFirstNeighbor(int v) {
  if(v != -1) {
    Edge<T,E> *p = nodeTable[v].adj; // 對應連結串列第一個邊結點
    if(p != NULL) // 存在,返回第一個鄰接頂點
      return p->dest;
  }
  return -1; // 第一個鄰接頂點不存在
}
 
// 取頂點v的鄰接頂點w的下一鄰接頂點
template <class T,E>::getNextNeighbor(int v,int w) {
  if(v != -1) {
    Edge<T,E> *p = nodeTable[v].adj; // 對應連結串列第一個邊結點
    while(p != NULL && p->dest != w) // 尋找鄰接頂點w
      p = p->link;
    if(p != NULL && p->link != NULL)
      return p->link->dest; // 返回下一個鄰接頂點
  }
  return -1; // 下一個鄰接頂點不存在
}
 
// 給出頂點vertex在圖中的位置
template <class T,E>::getVertexPos(const T vertex) {
  for(int i = 0; i < numVertices; i++)
    if(nodeTable[i].data == vertex)
      return i;
  return -1;
}
 
// 當前頂點數
template <class T,E>::numberOfVertices() {
  return numVertices;
}
 
#endif /* Graph_h */

2.Bellman-Ford.h

#ifndef Bellman_Ford_h
#define Bellman_Ford_h
#include "Graph.h"
 
// Bellman-Ford演算法
template<class T,class E>
void BellmanFord(Graphlnk<T,E> &G,int v,E dist[],int path[]) {
  int i,u,n = G.numberOfVertices();
  E w;
  
  // 1.初始化,將頂點v作為u頂點(存在<v,u>有向邊)的上一個頂點,記錄路徑
  for(i = 0; i < n; i++) {
    dist[i] = G.getWeight(v,i);
    if(i != v && dist[i] < G.maxValue)
      path[i] = v;
    else
      path[i] = -1;
  }
  // 2.迭代求解:反覆對邊集E中的每條邊進行鬆弛操作,使得頂點集V中的每個頂點的最短距離估計值逐步逼近其最短距離;(執行n-1次,因為上面算是1次:k=1,所以,k從2開始)
  bool isFlag; // 監視該輪dist陣列是否有變化
  for(k = 2; k < n; k++) {
    isFlag = false;
    for(u = 0; u < n; u++) { // 遍歷頂點,找不是v的頂點
      if(u != v) {
        for(i = 0; i < n; i++) {
          w = G.getWeight(i,u);
          if(w != 0 && w < G.maxValue && dist[u] > dist[i] + w) {
            // 存在<i,u>邊,並且繞過i,使得路徑更短,就修改u頂點的最短路徑
            // w可能是負權值,如果i和u是同一頂點,則w是0,排除同一頂點的情況
            // 也可以不寫w!=0,因為同一頂點,w=0,dist[u]==dist[i]+w會不滿足
            // dist[u] > dist[i] + w這個條件
            dist[u] = dist[i] + w;
            path[u] = i; // 記憶路徑
            isFlag = true;
          }
        } // 第3重迴圈
      }
    } // 第2重迴圈
    if(isFlag == false) // 如果dist陣列沒有變化,說明各個頂點已求得最短路徑
      break;
  } // 第1重for迴圈
}
 
// 從path陣列讀取最短路徑的演算法
template <class T,class E>
void printShortestPath(Graphlnk<T,n = G.numberOfVertices();
  int *d = new int[n];
  
  cout << "從頂點" << G.getValue(v) << "到其他各頂點的最短路徑為:" << endl;
  for(i = 0; i < n; i++) {
    if(i != v) { // 如果不是頂點v
      j = i;
      k = 0;
      while(j != v) {
        d[k++] = j;
        j = path[j];
      }
      cout << "頂點" << G.getValue(i) << "的最短路徑為:" << G.getValue(v);
      while(k > 0)
        cout << "->" << G.getValue(d[--k]);
      cout << ",最短路徑長度為:" << dist[i] << endl;
    }
  }
}
#endif /* Bellman_Ford_h */

3.main.cpp

/*
 測試資料:
 7 10
 0 1 2 3 4 5 6
 0 1 6
 0 2 5
 0 3 5
 1 4 -1
 2 1 -2
 2 4 1
 3 2 -2
 3 5 -1
 4 6 3
 5 6 3
 */
 
#include "Bellman-Ford.h"
 
const int maxSize = 40;
 
int main(int argc,const char * argv[]) {
  Graphlnk<char,int> G; // 宣告圖物件
  int dist[maxSize],path[maxSize],v;
  char u0;
  
  // 建立圖
  G.inputGraph();
  cout << "圖的資訊如下:" << endl;
  G.outputGraph();
  cout << "請輸入起始頂點u0:" << endl;
  cin >> u0;
  v = G.getVertexPos(u0); // 取得起始頂點的位置
  // 我把dist陣列放到有向圖標頭檔案中,方便建立有向圖時,同時初始化dist陣列
  BellmanFord(G,v,dist,path); // 呼叫BellmanFord函式
  printShortestPath(G,path); // 輸出到各個頂點的最短路徑
  return 0;
}

測試結果:

C++計算任意權值的單源最短路徑(Bellman-Ford)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。