SPFA算法记录最短路径 | Eternal_zttz

SPFA算法记录最短路径

路径记录方法:用path[]数组依次记录前驱节点,当找到最短路后,由终点倒推,直到找到起点,可以利用一个栈来维护此过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <queue>
#include <cstdio>
#include <stack>
#include <cstring>
#define M 1000005
#define N 100005
#define INF 999999999
using namespace std;
struct node {
int u,v,w,next;
};
int head[N],len[N],pre[N];
bool vis[N];
int n,m,cnt,s = 1;
void add(node edge[],int u,int v,int w){
edge[cnt] = {u,v,w,head[u]};
head[u] = cnt++;
}
void SPFA(queue<int>q,node edge[]){
q.push(s);
vis[s] = true;
for (int i=1;i<=n;i++)
len[i] = INF;
len[s] = 0;
while(!q.empty()){
int u = q.front();
q.pop();
vis[u] = false;
for (int i = head[u];i>0;i=edge[i].next){
int v = edge[i].v;
int w = edge[i].w;
if(len[v]> len[u]+w){
len[v] =len[u]+w;
pre[v] = u;//记录v的前驱节点为u
if(!vis[v]){
vis[v] =true;
q.push(v);
}
}
}
}
}
int main(){
scanf("%d %d",&n,&m);
node edge[m+1];
cnt = 1;
memset(head, 0, sizeof(head));
memset(len,0,sizeof(len));
memset(vis,false,sizeof(vis));
memset(pre,-1,sizeof(pre));
queue<int>q;
for (int i =1;i<=m;i++){
int u,v,w;
scanf("%d %d %d",&u,&v,&w);
add(edge,u,v,w);
//add(edge,v,u,w);
}
int start,end;
while(~scanf("%d %d",&start,&end)){
s = start;
SPFA(q, edge);
if(start == end){
printf("从%d 到%d的最短路线:%d\n",start,end,start);
printf("最短路径:%d",0);
}else{
stack<int> path;
path.push(end);
int now = pre[end];//now 为end的前驱节点,即倒数第二个节点
while(1){
path.push(now);
if(now == start)//找到起点,退出
break;
now = pre[now];//依次寻找上一个节点的前驱节点
}
printf("从%d到%d的最短路线:%d",start,end,start);
path.pop();
while(!path.empty()){
printf("-->%d",path.top());
path.pop();
}
printf("\n");
printf("最短路径:%d\n",len[end]);
}
}
}

-------------The End-------------