标签:
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 49478 Accepted Submission(s):
21783
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #define M 105 5 #define MAX 0x3f3f3f3f 6 using namespace std; 7 int n,map[M][M]; 8 void floyed() //直接暴力,要求数据小于100 9 { 10 int i,j,k; 11 for(k=1; k<=n; k++) 12 for(i=1; i<=n; i++) 13 for(j=1; j<=n; j++) 14 { 15 if(map[i][j]>map[i][k]+map[k][j]) //注意这个顺序,改了会错 16 map[i][j]=map[i][k]+map[k][j]; 17 } 18 } 19 20 int main() 21 { 22 int m,i,j; 23 while(~scanf("%d%d",&n,&m)) 24 { 25 if(n==0&&m==0) 26 break; 27 for(i=1; i<=n; i++) 28 for(j=1; j<=n; j++) 29 { 30 if(i==j) 31 map[i][j]=0; 32 else 33 map[i][j]=MAX; 34 } 35 int a,b,c; 36 for(i=0; i<m; i++) 37 { 38 scanf("%d%d%d",&a,&b,&c); 39 if(map[a][b]>c) 40 map[a][b]=map[b][a]=c; 41 } 42 floyed(); 43 printf("%d\n",map[1][n]); 44 } 45 return 0; 46 }
2.迪杰斯特拉
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #define M 105 5 #define MAX 0x3f3f3f3f 6 using namespace std; 7 int map[M][M],vis[M],dis[M]; 8 int main() 9 { 10 int n,m,i,j; 11 while(~scanf("%d%d",&n,&m)) 12 { 13 if(n==0&&m==0) 14 break; 15 memset(vis,0,sizeof(vis)); 16 memset(dis,0,sizeof(dis)); 17 for(i=1; i<=n; i++) 18 for(j=1; j<=n; j++) 19 { 20 if(i==j) 21 map[i][j]=0; 22 else 23 map[i][j]=MAX; 24 } 25 int a,b,c; 26 for(i=0; i<m; i++) 27 { 28 scanf("%d%d%d",&a,&b,&c); 29 if(map[a][b]>c) 30 map[a][b]=map[b][a]=c; 31 } 32 vis[1]=1; 33 for(i=1; i<=n; i++) 34 dis[i]=map[1][i]; 35 int min,t; 36 for(i=1; i<=n; i++) 37 { 38 min=MAX; 39 for(j=1; j<=n; j++) 40 if(!vis[j]&&min>dis[j]) 41 { 42 min=dis[j]; 43 t=j; 44 } 45 vis[t]=1; 46 for(j=1; j<=n; j++) 47 if(!vis[j]&&map[t][j]<MAX) 48 if(dis[j]>map[t][j]+dis[t]) 49 dis[j]=map[t][j]+dis[t]; 50 } 51 printf("%d\n",dis[n]); 52 } 53 return 0; 54 }
标签:
原文地址:http://www.cnblogs.com/pshw/p/5369937.html