hdu 2066 一个人的旅行(最短路径 Dijkstra算法)

思路:Dijkstra求最短路径,将0节点作为原点,求出到各个点的距离。


#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define inf 0x3fffffff
#define N 1005
int T,S,D,n,map[N][N],vis[N],cast[N],s[N],e[N];
void Dijkstra()
{
    int i,j,minn,pos;
    memset(vis,0,sizeof(vis));
    vis[0] = 1;
    for(i = 0; i<=n; i++)
        cast[i] = map[0][i];
    for(i = 1; i<=n; i++)
    {
        minn = inf;
        for(j = 1; j<=n; j++)
        {
            if(cast[j]<minn && !vis[j])
            {
                pos = j;
                minn = cast[j];
            }
        }
        vis[pos] = 1;
        for(j = 1; j<=n; j++)
        {
            if(cast[pos]+map[pos][j]<cast[j] && !vis[j])
                cast[j] = cast[pos]+map[pos][j];
        }
    }
}

int main()
{
    int x,y,z;
    while(~scanf("%d%d%d",&T,&S,&D))
    {
        n = 0;
        for(int i = 0; i<N; i++)
        {
            for(int j = 0; j<N; j++)
                map[i][j] = inf;
            map[i][i] = 0;
        }
        while(T--)
        {
            scanf("%d%d%d",&x,&y,&z);
            n = max(max(n,x),y);//n标记节点个数
            if(z<map[x][y])
                map[x][y] = map[y][x] = z;
        }

        for(int i = 0; i<S; i++)
        {
            scanf("%d",&s[i]);
            map[0][s[i]] = map[s[i]][0] = 0;
        }
        for(int i = 0; i<D; i++)
            scanf("%d",&e[i]);
        Dijkstra();
        int minn = inf;
        for(int i = 0; i<D; i++)
            minn = min(minn,cast[e[i]]);
        printf("%d\n",minn);
    }

    return 0;
}

    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/u014552756/article/details/50099443
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞