gpt4 book ai didi

c++ - Dijkstra 的问题,找到所有最小路径

转载 作者:太空狗 更新时间:2023-10-29 23:06:13 26 4
gpt4 key购买 nike

我们这里有一个问题,我们试图找到图中从一个节点到另一个节点的所有最短路径。我们已经实现了 dijkstra,但我们真的不知道如何找到它们。

我们必须使用 BFS 吗?

#include <vector>
#include <iostream>
#include <queue>
using namespace std;

typedef pair <int, int> dist_node;
typedef pair <int, int> edge;
const int MAXN = 10000;
const int INF = 1 << 30;
vector <edge> g[MAXN];
int d[MAXN];
int p[MAXN];

int dijkstra(int s, int n,int t){
for (int i = 0; i <= n; ++i){
d[i] = INF; p[i] = -1;
}
priority_queue < dist_node, vector <dist_node>,greater<dist_node> > q;
d[s] = 0;
q.push(dist_node(0, s));
while (!q.empty()){
int dist = q.top().first;
int cur = q.top().second;
q.pop();
if (dist > d[cur]) continue;
for (int i = 0; i < g[cur].size(); ++i){
int next = g[cur][i].first;
int w_extra = g[cur][i].second;
if (d[cur] + w_extra < d[next]){
d[next] = d[cur] + w_extra;
p[next] = cur;
q.push(dist_node(d[next], next));
}
}
}
return d[t];
}

vector <int> findpath (int t){
vector <int> path;
int cur=t;
while(cur != -1){
path.push_back(cur);
cur = p[cur];
}
reverse(path.begin(), path.end());
return path;
}

这是我们的代码,我们认为我们必须修改它,但我们真的不知道在哪里。

最佳答案

目前,您只保存/检索您碰巧找到的最短路径之一。考虑这个例子:

4 nodes
0 -> 1
0 -> 2
1 -> 3
2 -> 3

很明显,您不能拥有单个 p[]每个位置的值,因为实际上第 4 个节点 ( 3 ) 有 2 个先前的有效节点: 12 .

因此您可以将其替换为 vector<int> p[MAXN];并按如下方式工作:

if (d[cur] + w_extra < d[next]){
d[next] = d[cur] + w_extra;
p[next].clear();
p[next].push_back(cur);
q.push(dist_node(d[next], next));
}
else if(d[cur] + w_extra == d[next]){
p[next].push_back(cur); // a new shortest way of hitting this same node
}

您还需要更新您的 findpath()功能,因为它需要处理导致多条路径的“分支”,根据图形可能是指数级的大量路径。如果你只需要打印路径,你可以这样做:

int answer[MAXN];

void findpath (int t, int depth){
if(t == -1){ // we reached the initial node of one shortest path
for(int i = depth-1; i >= 0; --i){
printf("%d ", answer[i]);
}
printf("%d\n", last_node); // the target end node of the search
return;
}
for(int i = p[t].size()-1; i >= 0; --i){
answer[depth] = p[t][i];
findpath(p[t][i], depth+1);
}
}

请注意,您需要执行 p[s].push_back(-1)在你的 dijkstra 的开头,除了在案例之间清除这个 vector 数组。

关于c++ - Dijkstra 的问题,找到所有最小路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16615179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com