ref:
1:
for(int i = 0; i < n; i++){int minDis = INF; //在当前未访问的点中,找到starting点的最小距离int closest; //在当前未访问的点中,找距离starting最近的点,即dist[closest][starting] = minDis
2:
if(vis[j] == 0){//以closest点为媒介,更新各个点到starting的dis和cos
注意在每次更新时,把这个媒介点记录下来了:
path[j] = closest;//从starting到j点的倒数第二个点是closest
3:
使用:
#define N 500#define INF 100000000
#include#define N 500#define INF 100000000int dist[N][N], cost[N][N];int vis[N];//visited int dis[N],cos[N]; //从starting到各个点的最小dist和最小costint path[N]; //从starting到各个点最短路径中的倒数第二个点 //从path[destination]依次回溯直到sourceint stack[1000]; //模拟栈进行路径输出int main(){ freopen("in.txt","r",stdin); int n, m, s, d; scanf("%d%d%d%d",&n,&m,&s,&d); for(int i = 0; i < n; i++){//初始化 for(int j = 0; j < n; j++){ dist[i][j] = dist[j][i] = INF; cost[i][j] = cost[j][i] = INF; } } for(int i = 0; i < m; i++){//暂不考虑重边 int a,b; scanf("%d%d",&a, &b); int tmpDis,tmpCost; scanf("%d", &tmpDis ); scanf("%d", &tmpCost); dist[a][b] = dist[b][a] = tmpDis; cost[a][b] = cost[b][a] = tmpCost; } for(int i = 0; i < n; i++){ dis[i] = dist[s][i]; cos[i] = cost[s][i]; vis[i] = 0; if(dis[i] < INF){//从starting到该点存在直接路径 path[i] = s; }else{ path[i] = -1; } } vis[s] = 1;//初始化起点 path[s] = -1; for(int i = 0; i < n; i++){ int minDis = INF; //在当前未访问的点中,找到starting点的最小距离 int closest; //在当前未访问的点中,找距离starting最近的点,即dist[closest][starting] = minDis for(int j = 0; j < n; j++){ if(vis[j] == 0 && dis[j] < minDis){ minDis = dis[j]; closest = j; } } if(closest == d){//如果恰巧closest就是destination,那就破案了 break; } vis[closest] = 1;//访问了closest点 for(int j = 0; j < n; j++){ if(vis[j] == 0){//以closest点为媒介,更新各个点到starting的dis和cos if( (dis[j] > dis[closest] + dist[closest][j]) || //距离短了 (dis[j] == dis[closest] + dist[closest][j] && cos[j] > cos[closest] + cost[closest][j] //cost少了 )){ dis[j] = dis[closest] + dist[closest][j]; cos[j] = cos[closest] + cost[closest][j]; path[j] = closest;//从starting到j点的倒数第二个点是closest } } } } int tmp = d; int top = 0; while( path[tmp] != -1){ stack[top++] = path[tmp]; tmp = path[tmp]; } for(int i = top-1; i >= 0; i--){ printf("%d ",stack[i]); } printf("%d ",d); printf("%d %d",dis[d], cos[d]); return 0;}