[英]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.