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