首页 > 代码库 > SPFA 最短路径打印方法
SPFA 最短路径打印方法
#include <iostream>#include <cstdlib>#include <cstdio>#include <algorithm>#include <vector>#include <queue>#include <cmath>#include <cstring>using namespace std;#define INF 0xfffffff#define maxn 40struct Edge{ int e, w; Edge(int e=0,int w=0) : e(e), w(w) {}};int Path[maxn], n, dist[maxn];bool vis[maxn];vector<Edge> G[maxn];void Spfa(int Star,int End){ Edge P, Pn; dist[Star] = 0; queue<Edge> Q; Q.push(Edge(Star,0)); while( !Q.empty() ) { P = Q.front(); Q.pop(); vis[P.e] = true; int len = G[P.e].size(); for(int i=0; i<len; i++) { Pn = G[P.e][i]; if(dist[Pn.e] > dist[P.e] + Pn.w) { dist[Pn.e] = dist[P.e] + Pn.w; Path[Pn.e] = P.e; if( !vis[Pn.e] ) { Q.push(Pn); vis[Pn.e] = true; } } } }}void PutPath(int Star,int End){ if(Star == End) { printf("%d", Star); return ; } PutPath(Star, Path[End]); printf("---->%d", End);}void Init(){ for(int i=1; i<=n; i++) { G[i].clear(); dist[i] = INF; vis[i] = false; Path[i] = i; }}int main(){ int m; cin >> n >> m; Init(); for(int i=1; i<=m; i++) { int a, b, c; cin >> a >> b >> c; G[a].push_back(Edge(b,c)); } Spfa(1, n); printf("%d\n", dist[n]); PutPath(1,n); return 0;}/*4 31 2 12 3 13 4 1*/
SPFA 最短路径打印方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。