hdu2066一个人的旅行

枚举所有相邻城市,作为起点,多次spfa,然后每次在想去的城市中找出spfa后的距离起点最短的花费时间

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

#define MAX 1005
#define INF 1<<30

int T,S,D;

struct Edge{
    int to,time,next;
}edge[MAX*2];
int head[MAX],tol;

int s_city[MAX],d_city[MAX];

void add(int u,int v,int time)
{
    edge[tol].to = v;
    edge[tol].time = time;
    edge[tol].next = head[u];
    head[u] = tol ++;
}

int dis[MAX];
bool flag[MAX];

int spfa(int src)
{
    for(int i = 0; i < MAX; i ++) dis[i] = INF;
    memset(flag,false,sizeof(flag));
    flag[src] = true;
    dis[src] = 0;

    queue<int>q;
    q.push(src);

    while(!q.empty())
    {
        int u = q.front(); q.pop();
        flag[u] = false;

        for(int i = head[u]; i != -1; i = edge[i].next)
        {
            int v = edge[i].to,time = edge[i].time;
            if(dis[u] + time < dis[v])
            {
                dis[v] = dis[u]+time;
                if(!flag[v]){
                    q.push(v); flag[v] = true;
                }
            }
        }
    }

    int ans = INF;
    for(int i = 0; i < D; i ++)
    {
        if(dis[d_city[i]] < ans) ans = dis[d_city[i]];
    }
    return ans;
}

int main()
{
    int a,b,time;
    while(cin >> T >> S >> D)
    {
        memset(head,-1,sizeof(head));
        tol = 0;

        while(T--){
            cin >> a >> b >> time;
            add(a,b,time); add(b,a,time);
        }
        for(int i = 0; i < S; i ++) cin >> s_city[i];
        for(int i = 0; i < D; i ++) cin >> d_city[i];

        //ans 无穷大,对于每一个相邻城市作为源点spfa,并且返回到D个想去的城市中的最小时间
        int ans = INF;
        for(int i = 0; i < S; i ++)
        {
            int temp = spfa(s_city[i]);
            if(temp < ans) ans = temp;
        }
        cout << ans <<endl;
    }
    return 0;
}


你可能感兴趣的:(hdu2066一个人的旅行)