标签:
感觉Floyd算法比Dijkstra还要简单。。
唯一需要注意的是,初始的距离默认值不要设过大,否则溢出就不好了,根据题意,只要大于10^3即可
代码:
1 #include <iostream> 2 #include <cstring> 3 4 using namespace std; 5 6 #define MAX_POINT 1024 7 #define MAX_EDGE 16384 8 9 int N, M; 10 int d[MAX_POINT][MAX_POINT]; 11 12 void floyd() { 13 for (int k = 1; k <= N; k++) { 14 for (int i = 1; i <= N; i++) { 15 for (int j = 1; j <= N; j++) { 16 if (k == i || i == j || j == k) 17 continue; 18 d[i][j] = min(d[i][j], d[i][k] + d[k][j]); 19 } 20 } 21 } 22 } 23 24 int main() { 25 memset(d, 1, sizeof(d)); 26 scanf("%d%d", &N, &M); 27 for (int i = 1; i <= N; i++) 28 d[i][i] = 0; 29 for (int i = 0; i < M; i++) { 30 int a, b, len; 31 scanf("%d%d%d", &a, &b, &len); 32 d[a][b] = d[b][a] = min(d[a][b], len); 33 } 34 35 floyd(); 36 37 for (int i = 1; i <= N; i++) { 38 for (int j = 1; j < N; j++) 39 printf("%d ", d[i][j]); 40 printf("%d\n", d[i][N]); 41 } 42 return 0; 43 }
标签:
原文地址:http://www.cnblogs.com/boring09/p/4396505.html