zoukankan      html  css  js  c++  java
  • HDU 2066 最短路(floyd算法+优化)

    link:https://vjudge.net/problem/HDU-2066#author=haochengqian

    题意 从任意一个邻居家出发 到达任意一个终点的 最小距离

    解析 求多源最短路 我想到的是Floyd算法 但是题目给出的n的大小不确定 所以图很稀疏 会有很多孤立点 会多跑很多没用的路径 需要优化一下 不然会超时

    #include <iostream>
    #include <cstring>
    #include <queue>
    #include <algorithm>
    
    using namespace std;
    
    const int maxn=1000+10;
    const int INF=0x3f3f3f3f;
    int cost[maxn][maxn];
    int Max,t,s,d;
    int n;
    int l[maxn],r[maxn];
    
    void floyd()
    {
        for(int k=1;k<=n;k++)
        {
            for(int i=1;i<=n;i++)
            {
                if(cost[i][k]!=INF)//剪枝优化,不要放在for循环里面!!!
                {
                    for(int j=1;j<=n;j++)
                    {
                        cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j]);
                    }
                }
    
            }
        }
    }
    
    void init()
    {
        for(int i=0;i<=1005;i++)
        {
            for(int j=0;j<=1005;j++)
            {
                if(i==j) cost[i][j]=0;
                else cost[i][j]=INF;
            }
        }
    }
    
    int main()
    {
    
        ios::sync_with_stdio(false);cin.tie(0);
        while(cin>>t>>s>>d)
        {
            n=0;
            init();
            while(t--)
            {
                int u,v,w;
                cin>>u>>v>>w;
                n=max(u,max(n,v));
                if(cost[u][v]>w) cost[u][v]=cost[v][u]=w;
    
            }
            for(int i=0;i<s;i++)
            {
                cin>>l[i];
            }
            for(int i=0;i<d;i++)
            {
                cin>>r[i];
            }
            floyd();
            int ans=INF;
            for(int i=0;i<s;i++)
            {
                for(int j=0;j<d;j++)
                {
                    ans=min(ans,cost[l[i]][r[j]]);
                }
            }
            cout<<ans<<endl;
        }
    
        return 0;
    }
  • 相关阅读:
    【读书笔记】《思考,快与慢》
    【2020-12-09】别人看不上的,正是绝佳机会
    员工的重要性
    二叉树的堂兄弟节点
    占位
    数组中重复的数字
    从上到下打印二叉树
    Python生成exe
    二叉搜索树节点最小距离
    第N个斐波那契数
  • 原文地址:https://www.cnblogs.com/Fy1999/p/9460435.html
Copyright © 2011-2022 走看看