zoukankan      html  css  js  c++  java
  • 畅通工程续 -- HDU 1874 floyd

    题目大意:

    现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。

    思路:

    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
    ", mp[from][to]);
            else printf("-1
    ");
        }
    }
    View Code

    如有疑问,欢迎评论指出!

    化繁为简 大巧不工
  • 相关阅读:
    使用 Vim 搭建 JavaScript 开发环境
    SpaceVim 语言模块 erlang
    SpaceVim 语言模块 lua
    SpaceVim 语言模块 python
    SpaceVim 语言模块 elixir
    SpaceVim 语言模块 dart
    SpaceVim 语言模块 elm
    如何配置 SpaceVim
    彻底理解浏览器缓存机制
    react-创建react元素
  • 原文地址:https://www.cnblogs.com/mpeter/p/10386508.html
Copyright © 2011-2022 走看看