标签:
hdu 2544
求点1到点n的最短路
Sample Input
2 1 //结点数 边数
1 2 3 //u v w
3 3
1 2 5
2 3 5
3 1 2
0 0
Sample Output
3
2
1 # include <iostream> 2 # include <cstdio> 3 # include <cstring> 4 # include <algorithm> 5 # include <cmath> 6 # define LL long long 7 using namespace std ; 8 9 const int MAXN=200; 10 const int INF=0x3f3f3f3f; 11 int n ; 12 bool vis[MAXN]; 13 int cost[MAXN][MAXN] ; 14 int lowcost[MAXN] ; 15 int pre[MAXN]; 16 void Dijkstra(int beg) 17 { 18 for(int i=0;i<n;i++) 19 { 20 lowcost[i]=INF;vis[i]=false;pre[i]=-1; 21 } 22 lowcost[beg]=0; 23 for(int j=0;j<n;j++) 24 { 25 int k=-1; 26 int Min=INF; 27 for(int i=0;i<n;i++) 28 if(!vis[i]&&lowcost[i]<Min) 29 { 30 Min=lowcost[i]; 31 k=i; 32 } 33 if(k==-1)break; 34 vis[k]=true; 35 for(int i=0;i<n;i++) 36 if(!vis[i]&&lowcost[k]+cost[k][i]<lowcost[i]) 37 { 38 lowcost[i]=lowcost[k]+cost[k][i]; 39 pre[i]=k; 40 } 41 } 42 } 43 44 int main () 45 { 46 // freopen("in.txt","r",stdin) ; 47 int m ; 48 while (scanf("%d %d" , &n , &m) !=EOF) 49 { 50 if (n==0 && m==0) 51 break ; 52 int u , v , w ; 53 int i , j ; 54 for (i = 0 ; i < n ; i++) 55 for (j = 0 ; j < n ; j++) 56 cost[i][j] = INF ; 57 while(m--) 58 { 59 scanf("%d%d%d" , &u , &v , &w) ; 60 if (w < cost[u][v]) //防止重边 61 { 62 cost[u][v] = w ; 63 cost[v][u] = w ; 64 } 65 } 66 Dijkstra(0) ; 67 printf("%d\n" , lowcost[n-1]) ; 68 } 69 70 return 0 ; 71 }
hdu 1874
输出最短需要行走的距离。如果不存在从S到T的路线,就输出-1.
Sample Input
3 3 //结点数 边数
0 1 1//u v w
0 2 3
1 2 1
0 2 //起点 终点
3 1
0 1 1
1 2
Sample Output
2
-1
1 # include <iostream> 2 # include <cstdio> 3 # include <cstring> 4 # include <algorithm> 5 # include <cmath> 6 # define LL long long 7 using namespace std ; 8 9 const int MAXN=300; 10 const int INF=0x3f3f3f3f; 11 int n ; 12 bool vis[MAXN]; 13 int cost[MAXN][MAXN] ; 14 int lowcost[MAXN] ; 15 int pre[MAXN]; 16 void Dijkstra(int beg) 17 { 18 for(int i=0;i<n;i++) 19 { 20 lowcost[i]=INF;vis[i]=false;pre[i]=-1; 21 } 22 lowcost[beg]=0; 23 for(int j=0;j<n;j++) 24 { 25 int k=-1; 26 int Min=INF; 27 for(int i=0;i<n;i++) 28 if(!vis[i]&&lowcost[i]<Min) 29 { 30 Min=lowcost[i]; 31 k=i; 32 } 33 if(k==-1) 34 break ; 35 vis[k]=true; 36 for(int i=0;i<n;i++) 37 if(!vis[i]&&lowcost[k]+cost[k][i]<lowcost[i]) 38 { 39 lowcost[i]=lowcost[k]+cost[k][i]; 40 pre[i]=k; 41 } 42 } 43 44 } 45 46 int main () 47 { 48 // freopen("in.txt","r",stdin) ; 49 int m ; 50 while (scanf("%d %d" , &n , &m) !=EOF) 51 { 52 53 int u , v , w ; 54 int i , j ; 55 for (i = 0 ; i < n ; i++) 56 for (j = 0 ; j < n ; j++) 57 cost[i][j] = INF ; 58 while(m--) 59 { 60 scanf("%d%d%d" , &u , &v , &w) ; 61 if (w < cost[u][v]) //防止重边 62 { 63 cost[u][v] = w ; 64 cost[v][u] = w ; 65 } 66 } 67 scanf("%d %d" , &u , &v) ; 68 Dijkstra(u) ; 69 if (lowcost[v] != INF) 70 printf("%d\n" , lowcost[v]) ; 71 else 72 printf("-1\n") ; 73 } 74 75 return 0 ; 76 }
hdu 2544 hdu 1874 Dijkstra 模板题
标签:
原文地址:http://www.cnblogs.com/-Buff-/p/4586817.html