本文的基础知识见:算法导论第24章:单源最短路径
入门题:HDOJ 2544 最短路
Dijkstra算法
算法实现:邻接矩阵 + 维护结点的d值 + 每次取min{d}入队 & 松弛
运行时间:未用优先队列,O(V²)
#include <iostream> #include <cstring> using namespace std; const int inf = 1e8; int edge[105][105]; int d[105]; bool vis[105]; int n,m,a,b,c,cur,imin; void init() { memset(edge,0,sizeof(edge)); memset(vis,0,sizeof(vis)); for(int i=1; i<105; ++i) d[i] = inf; cur = 1; vis[1] = 1; d[1] = 0; for(int i=0; i<m; ++i) { cin>>a>>b>>c; if(edge[a][b]==0 || edge[a][b] > c) edge[a][b] = edge[b][a] = c; } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); while(cin>>n>>m && n) { init(); for(int i=1; i<=n-1; ++i) { for(int j=1; j<=n; ++j) { if(vis[j] == 0 && edge[cur][j] && d[j] > d[cur] + edge[cur][j]) d[j] = d[cur] + edge[cur][j]; } imin = inf; for(int i=1; i<=n; ++i) { if(vis[i]==0 && imin > d[i]) { imin = d[i]; cur = i; } } if(cur == n) break; vis[cur] = 1; } cout<<d[n]<<"\n"; } return 0; }
Bellman-Ford算法
Edge结构体 + 松弛所有边V-1次
#include <iostream> using namespace std; struct Edge { int begin,end,length; } edge[10005]; int n,m,a,b,c; const int inf = 1e8; int d[105]; void init() { for(int i=1; i<105; ++i) d[i] = inf; for(int i=0; i<m; ++i) cin>>edge[i].begin>>edge[i].end>>edge[i].length; d[1] = 0; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); while(cin>>n>>m && n) { init(); for(int i=1; i<=n-1; ++i) { for(int j=0; j<m; ++j) { if(d[edge[j].begin] < inf && d[edge[j].begin] + edge[j].length < d[edge[j].end]) d[edge[j].end] = d[edge[j].begin] + edge[j].length; if(d[edge[j].end] < inf && d[edge[j].end] + edge[j].length < d[edge[j].begin]) d[edge[j].begin] = d[edge[j].end] + edge[j].length; } } cout<<d[n]<<"\n"; } return 0; }