題目大意:ios
如今,已知起點和終點,請你計算出要從起點到終點,最短鬚要行走多少距離。算法
思路:ide
floyd算法模板題,這是一個犧牲空間換取時間的算法,本質是動態規劃。spa
AC代碼:code
#include <iostream> #include <cstdio> #include <string.h> using namespace std; const int MX = 1000+10; const int INF = 0x3f3f3f3f; int n, m; int mp[MX][MX]; void floyd() { for(int k = 0; k < n; ++k) for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) mp[i][j] = min(mp[i][j], mp[i][k]+mp[k][j]); } int main() { while(scanf("%d%d", &n, &m) != EOF) { memset(mp, INF, sizeof(mp)); for(int i = 0; i < n; ++i) mp[i][i] = 0; for(int i = 0; i < m; ++i) { int from, to, cost; scanf("%d%d%d", &from, &to, &cost); if(mp[from][to] > cost) mp[from][to] = mp[to][from] = cost; //這裏注意A到B可能有多條路能到! } floyd(); int from, to; scanf("%d%d", &from, &to); if(mp[from][to] != INF) printf("%d\n", mp[from][to]); else printf("-1\n"); } }
若有疑問,歡迎評論指出!blog