标签:des style blog http java color os strong
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
3 2
一道纯粹的最短路径入门题。
Dijkstra:
#include<cstdio> #include<cstring> #include<cmath> #include<iostream> #include<algorithm> #include<queue> #include<vector> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 10000; int n, m; int x, y, cost; int edge[maxn][maxn];//邻接矩阵 int vist[maxn];//记录顶点是否在集合中 int dis[maxn];//记录权值 void init() { for(int i=1; i<=n; i++) { vist[i] = 0; dis[i] = INF; for(int j=1; j<=n; j++) edge[i][j] = INF; } for(int i=1; i<=m; i++) { scanf("%d%d%d", &x, &y, &cost); edge[x][y] = edge[y][x] = cost; } } void Dijkstra(int v0) { dis[v0] = 0; vist[v0] = 1;//顶点1如集合 for(int i=2; i<=n; i++)//求出顶点v0与其他n-1条最短路径 { int min = INF; int k; for(int j=1; j<=n; j++) { if( !vist[j] && dis[j]<min ) { min = dis[j]; k = j; } } vist[k] = 1;//顶点k进入集合 for(int j=1; j<=n; j++) { if( !vist[j] && edge[k][j]<INF && dis[j]>dis[k]+edge[k][j]) dis[j] = dis[k] + edge[k][j]; } } } int main() { while(scanf("%d%d", &n, &m)==2 &&n &&m) { init(); Dijkstra(1); printf("%d\n", dis[n]); } return 0; }
#include<cstdio> #include<iostream> #include<cstring> #include<queue> #include<algorithm> #include<vector> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 105; int map[maxn][maxn]; int main() { int n, m; while( scanf("%d%d", &n, &m)==2 &&n &&m ) { int a, b, c; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) map[i][j] = INF; for(int i=1; i<=m; i++) { scanf("%d%d%d", &a, &b, &c); map[a][b] = map[b][a] = c; } for(int k=1; k<=n; k++) for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) map[i][j] = min( map[i][j], map[i][k] + map[k][j] ); printf("%d\n", map[1][n]); } return 0; }
HDU 2544:最短路( 最短路径入门 &&Dijkstra && floyd ),布布扣,bubuko.com
HDU 2544:最短路( 最短路径入门 &&Dijkstra && floyd )
标签:des style blog http java color os strong
原文地址:http://blog.csdn.net/u013487051/article/details/38128105