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;
}

 

posted @ 2018-08-11 17:30  Somnus、M  阅读(207)  评论(0编辑  收藏  举报