Hdu 2066 一个人的旅行

Problem地址 : http://acm.hdu.edu.cn/showproblem.php?pid=2066

 

这道题可以使用最短路解题,因此可以使用Dijstra算法。

因为存在几个与家相连的地方,假设这个地方叫A,那我们可以设想家到A的距离为0,那此题就变成从A到目的地,变成从家到目的地。因为A的数量是不定的,但家就只有一个,所以采用这种措施可以简化题目。

另外此题中提供的路径,比如A到B,是可以有多条的,因此,A到B之间需要采取最短的那条。

题目中给出了几个主人公想去的地方,仔细想一下或许可以想到,这几个地方中可能存在几个到达不了的地方,这些不能到达的地方的存在可能会影响我们的判断,因此需要注意。

 

#include <iostream>

#include <cstring>

#include <cstdio>

#include <queue>



using namespace std;



const int MAXN = 1000 + 50;

const int INF = 65535;

const int HOME = 0; // 起点

int dis[MAXN][MAXN]; // 两点之间的距离

int path[MAXN]; // 家到任意一点的距离

int vis[ MAXN ]; // 是否访问了该点

int roads, T, S, D; // roads表示地点的最大编号



void ReadRoads() {

    memset( dis, -1, sizeof( dis ) );

    roads = -INF;

    int a, b, s;

    while( T -- ) {

        scanf( "%d%d%d", &a, &b, &s );

        if( dis[a][b]!=-1 && dis[a][b] < s ) {

            continue;

        }

        dis[a][b] = dis[b][a] = s;

        roads = roads > a ? roads : a;

        roads = roads > b ? roads : b;

    }

    while( S -- ) {

        scanf( "%d", &a );

        dis[HOME][a] = dis[a][HOME] = 0;

    }

}



void Dijstra() {

    memset( vis, false, sizeof( vis ) );

    memset( path, 0, sizeof( path ) );

    vis[0] = true;

    queue <int> q;

    q.push( HOME );

    int t, i;

    while( !q.empty() ) {

        t = q.front();

        q.pop();

        for( i=0; i<=roads; i++ ) {

            if( dis[ t ][ i ] != -1 ) {

                if( vis[i] ) {

                    path[i] = path[t]+dis[t][i] < path[i] ? path[t]+dis[t][i] : path[i];

                } else {

                    path[i] = path[t] + dis[t][i];

                    vis[i] = true;

                    q.push( i );

                }

            }

        }

    }

}



int GetMin() {

    int minC = INF;

    int tmpPos;

    while( D-- ) {

        scanf( "%d", &tmpPos );

        if( !vis[ tmpPos ] ) { // 存在不能到达的城市

            continue;

        }

        minC = minC < path[tmpPos] ? minC : path[ tmpPos ];

    }

    return minC;

}



int main()

{

    while( scanf( "%d%d%d", &T, &S, &D ) != EOF ) {

        ReadRoads();

        Dijkstra();

        printf( "%d\n", GetMin() );

    }

    return 0;

}

 

你可能感兴趣的:(HDU)