标签:hdu1874 floyd bellman-ford 最短路径 畅通工程续
3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
#include <stdio.h> #include <string.h> #define MAX 210 #define INF 100000000 int dp[MAX][MAX] ; void floyd(int n) { for(int k = 0 ; k < n ; ++k) { for(int i = 0 ; i < n ; ++i) { if(dp[i][k] == INF) { continue ; } for(int j = 0 ; j < n ; ++j) { if(dp[i][j]>dp[i][k]+dp[k][j]) { dp[i][j] = dp[i][k]+dp[k][j] ; } } } } } int main() { int n , m ; while(~scanf("%d%d",&n,&m)) { for(int i = 0 ; i <= n ; ++i) { for(int j = 0 ; j <= i ; ++j) { dp[i][j]=dp[j][i] = INF ; } dp[i][i] = 0 ; } for(int i = 0 ; i < m ; ++i) { int a , b , x ; scanf("%d%d%d",&a,&b,&x); if(dp[a][b] > x) //千万别忘了判重 dp[a][b] = dp[b][a] = x ; } floyd(n); int x, y ; scanf("%d%d",&x,&y); if(dp[x][y] == INF) { puts("-1") ; } else { printf("%d\n",dp[x][y]); } } return 0 ; }
#include <stdio.h> #include <string.h> #define MAX 210 #define INF 100000000 int graph[MAX][MAX] , dis[MAX]; void Bellman_Ford(int u , int n) { for(int i = 0 ; i < n ; ++i) { dis[i] = INF ; } dis[u] = 0 ; for(int k = 0 ; k < n-1 ; ++k) { for(int i = 0 ; i < n ; ++i) { for(int j = 0 ; j < n ; ++j) { if(dis[i]>dis[j]+graph[j][i]) { dis[i] = dis[j]+graph[j][i] ; } } } } } int main() { int n , m ; while(~scanf("%d%d",&n,&m)) { for(int i = 0 ; i <= n ; ++i) { for(int j = 0 ; j <= i ; ++j) { graph[i][j]=graph[j][i] = INF ; } graph[i][i] = 0 ; } for(int i = 0 ; i < m ; ++i) { int a , b , x ; scanf("%d%d%d",&a,&b,&x); if(graph[a][b] > x) //千万别忘了判重 graph[a][b] = graph[b][a] = x ; } int x, y ; scanf("%d%d",&x,&y); Bellman_Ford(x,n); if(dis[y] == INF) { puts("-1") ; } else { printf("%d\n",dis[y]); } } return 0 ; }
hdu 1874 畅通工程续 两种算法AC Floyd+Bellman-Ford算法 又是一波水题~~
标签:hdu1874 floyd bellman-ford 最短路径 畅通工程续
原文地址:http://blog.csdn.net/lionel_d/article/details/43868867