1. 程式人生 > >暢通工程續 -- HDU 1874 floyd

暢通工程續 -- HDU 1874 floyd

起點到終點 void 多少 stream eve 動態 距離 const else

題目大意:

現在,已知起點和終點,請你計算出要從起點到終點,最短需要行走多少距離。

思路:

floyd算法模板題,這是一個犧牲空間換取時間的算法,本質是動態規劃。

AC代碼:

技術分享圖片
#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"); } }
View Code

如有疑問,歡迎評論指出!

暢通工程續 -- HDU 1874 floyd