微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何找到加权图中是否有不止一条最短路径?

如何解决如何找到加权图中是否有不止一条最短路径?

我有一个无向加权图。

我正在使用 Dijkstra 算法来查找从源节点到目标节点的最短路径。

但我也想制作一个 bool 函数,它可以告诉我是否存在多个最短路径。

我写到现在的代码

#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 来实现这个想法是错误的?有没有不同的算法可以帮助我做到这一点?如果源节点和目标节点之间的最短路径不止一条,我只需要一个 true 和 false。

更新

示例输入

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

源-0

目的地 3

为此,destTo 向量输出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";

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。