簡體   English   中英

如何查找加權圖中是否存在多個最短路徑?

[英]How to find if there is more than one shortest path in a weighted graph?

我有一個無向加權圖。

我正在使用 Dijkstra 的算法來找到從源節點到目標節點的最短路徑。

但我也想做一個 bool function 可以告訴我是否有多個最短路徑。

我寫到現在的代碼

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n,m,source;
    cin >> n >> m;
    vector<pair<int,int> > g[n+1];  // 1-indexed adjacency list for of graph

    int a,b,wt;
    for(int i = 0; i<m ; i++){
        cin >> a >> b >> wt;
        g[a].push_back(make_pair(b,wt));
        g[b].push_back(make_pair(a,wt));
    }   
    
    cin >> source;
    
    // Dijkstra's algorithm begins from here
    priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > pq;// min-heap ; In pair => (dist,from)
    vector<int> distTo(n+1,INT_MAX);    // 1-indexed array for calculating shortest paths; 
    
    distTo[source] = 0;
    pq.push(make_pair(0,source));   // (dist,from)
    
    while( !pq.empty() ){
        int dist = pq.top().first;
        int prev = pq.top().second;
        pq.pop();
        
        vector<pair<int,int> >::iterator it;
        for( it = g[prev].begin() ; it != g[prev].end() ; it++){
            int next = it->first;
            int nextDist = it->second;
            if( distTo[next] > distTo[prev] + nextDist){
                distTo[next] = distTo[prev] + nextDist;
                pq.push(make_pair(distTo[next], next));
            }
        }
        
    }
    
    cout << "The distances from source, " << source << ", are : \n";
    for(int i = 1 ; i<=n ; i++) cout << distTo[i] << " ";
    cout << "\n";
    
    return 0;
}

我不需要不同最短路徑的路徑,只需要一個真假。

我閱讀了很多關於此的在線資源,從那里我了解到在算法中沒有條件何時

if( distTo[next] == distTo[prev] + nextDist)

所以當這種情況發生時,我應該將該節點添加到列表/二維向量中。

我無法實現這個想法,所以當有==條件時,我應該將該節點添加到什么? 我是否必須跟蹤整個路徑,然后將其與最短路徑進行比較?

如果可能的話,你能寫代碼並向我展示它是如何完成的嗎?

我用 Dijkstra 做這個想法錯了嗎? 有沒有不同的算法可以幫助我做到這一點? 如果源節點和目標節點之間的最短路徑不止一條,我只需要一個真假。

更新

示例輸入

4,4
0,1,3
1,2,1 
2,3,2 
0,2,4

源-0

目的地 3

為此, destTo向量 output 為0 3 4 6

您可以使用修改后的 Dijkstra 來跟蹤節點是否可以通過多條最短路徑到達。

最簡單的方法是使用bool容器:

vector<bool> multipath(n, false);

以及一些管理這些位的邏輯:

if( distTo[next] == distTo[prev] + nextDist){
  multipath[next] = true;
}

if( distTo[next] > distTo[prev] + nextDist){
  distTo[next] = distTo[prev] + nextDist;
  if(multipath[prev])
    multipath[next]=true;
  pq.push(make_pair(distTo[next], next));
}

然后以某種方式報告結果:

for(int i = 1 ; i<n ; i++){
  cout << distTo[i];
  if(multipath[i])
    cout << "*";
  cout << " ";
}
cout << "\n";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM