标签:style blog http color os io for div
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544
题目大意:找到两点间最短的距离值。
代码一:(dijkstra算法)
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 int n,Min,node[105],visit[105],map[105][105]; 5 void set() 6 { 7 for (int i=1; i<=n; i++) 8 { 9 node[i]=999999; 10 visit[i]=0; 11 for (int j=1; j<=n; j++) 12 map[i][j]=999999; 13 } 14 } 15 int dijkstra(int m) 16 { 17 int tm=m; 18 visit[m]=1; 19 node[m]=0; 20 for (int k=2; k<=n; k++) 21 { 22 Min=999999; 23 for (int i=1; i<=n; i++) 24 if (!visit[i]) 25 { 26 if (node[i]>map[tm][i]+node[tm]) 27 node[i]=map[tm][i]+node[tm]; 28 if (Min>node[i]) 29 { 30 Min=node[i]; 31 m=i; 32 } 33 } 34 visit[m]=1; 35 tm=m; 36 } 37 return node[1]; 38 } 39 int main () 40 { 41 int m,a,b,c; 42 while (scanf("%d%d",&n,&m),(n||m)) 43 { 44 set(); 45 while (m--) 46 { 47 scanf("%d%d%d",&a,&b,&c); 48 if (c<map[a][b]) 49 map[a][b]=map[b][a]=c; 50 } 51 printf("%d\n",dijkstra(n)); 52 } 53 }
代码二:(floyd算法)
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 int map[205][205]; 5 const int INF=9999999; 6 7 int main () 8 { 9 int n,m; 10 while(~scanf("%d%d",&n,&m)) 11 { 12 if (n==0&&m==0) 13 break; 14 for (int i=1; i<=n; i++) 15 for (int j=1; j<=n; j++) 16 { 17 if (i!=j) 18 map[i][j]=map[j][i]=INF; 19 else 20 map[i][j]=map[j][i]=0; 21 } 22 while (m--) 23 { 24 int a,b,c; 25 scanf("%d%d%d",&a,&b,&c); 26 if (map[a][b]>c) 27 map[a][b]=map[b][a]=c; 28 } 29 for (int k=1; k<=n; k++) 30 for (int i=1; i<=n; i++) 31 for (int j=1; j<=n; j++) 32 if (map[i][j]>map[i][k]+map[k][j]) 33 map[i][j]=map[j][i]=map[i][k]+map[k][j]; 34 printf ("%d\n",map[1][n]); 35 36 } 37 return 0; 38 }
hdu 2544 最短路 (dijkstra,floyd),布布扣,bubuko.com
标签:style blog http color os io for div
原文地址:http://www.cnblogs.com/qq-star/p/3907024.html