标签:
Dijkstra:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 const int mx=1000000; 6 int n,m; 7 int v[105],ans[105]; 8 int map[105][105]; 9 void f(int x) 10 { 11 v[x]=1; 12 int i,p,mn; 13 for (i=1;i<=n;i++) ans[i]=map[x][i]; 14 while (1) 15 { 16 mn=mx; 17 p=x; 18 for (i=1;i<=n;i++) 19 { 20 if (!v[i]&&ans[i]<mn) 21 { 22 p=i; 23 mn=ans[i]; 24 } 25 } 26 if (p==x) return ; 27 v[p]=1; 28 for (i=1;i<=n;i++) 29 { 30 if (!v[i]&&ans[i]>ans[p]+map[p][i]) 31 ans[i]=ans[p]+map[p][i]; 32 } 33 } 34 } 35 int main() 36 { 37 int i,j,a,b,c; 38 while (~scanf("%d%d",&n,&m)) 39 { 40 if (n==0&&m==0) return 0; 41 for (i=1;i<=n;i++) 42 for (j=1;j<=n;j++) 43 { 44 if (i==j) map[i][j]=0; 45 else map[i][j]=mx; 46 } 47 while (m--) 48 { 49 scanf("%d%d%d",&a,&b,&c); 50 if (map[a][b]>c) 51 map[a][b]=map[b][a]=c; 52 } 53 memset(v,0,sizeof(v)); 54 f(1); 55 printf("%d\n",ans[n]); 56 } 57 }
Floyd:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 int main() 6 { 7 int n,m,i,j,k,a,b,c; 8 int map[108][108]; 9 while (~scanf("%d%d",&n,&m)) 10 { 11 if (n==0&&m==0) return 0; 12 for (i=1;i<=n;i++) 13 for (j=1;j<=n;j++) map[i][j]=10000000; 14 while (m--) 15 { 16 scanf("%d%d%d",&a,&b,&c); 17 map[a][b]=map[b][a]=c; 18 } 19 for (k=1;k<=n;k++) 20 for (i=1;i<=n;i++) 21 for (j=1;j<=n;j++) 22 if (map[i][j]>map[i][k]+map[k][j]) 23 map[i][j]=map[i][k]+map[k][j]; 24 printf("%d\n",map[1][n]); 25 } 26 }
Dfs:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 int n,m,a,b,c,t; 6 int map[108][108],v[108]; 7 void dfs(int x,int p) 8 { 9 if (p>t) return ; 10 if (x==n) 11 { 12 t=p; 13 return ; 14 } 15 int i; 16 for (i=2;i<=n;i++) 17 { 18 if (!v[i]&&map[x][i]) 19 { 20 v[i]=1; 21 dfs(i,p+map[x][i]); 22 v[i]=0; 23 } 24 } 25 } 26 int main() 27 { 28 int i,j; 29 while (~scanf("%d%d",&n,&m)) 30 { 31 if (n==0&&m==0) return 0; 32 memset(map,0,sizeof(map)); 33 memset(v,0,sizeof(v)); 34 while (m--) 35 { 36 scanf("%d%d%d",&a,&b,&c); 37 map[a][b]=map[b][a]=c; 38 } 39 t=1000000; 40 dfs(1,0); 41 printf("%d\n",t); 42 } 43 }
hdu 2544 最短路(Dijkstra Or Floyd Or dfs)
标签:
原文地址:http://www.cnblogs.com/pblr/p/4748960.html