[POJ - 2387] L - Til the Cows Come Home(图论)

L - Til the Cows Come Home

POJ - 2387

Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.

Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.

Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.

Input

* Line 1: Two integers: T and N

* Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.

Output

* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.

Sample Input

5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

Sample Output

90

Hint

INPUT DETAILS:

There are five landmarks.

OUTPUT DETAILS:

Bessie can get home by following trails 4, 3, 2, and 1.

题目描述:

Bessie要从路标N回到路标1,求最短距离。Bessie对自己骑牛技术不自信,每条路只能走一次不能回头走。(既然最短距离,这个条件就可以忽略了)

分析:

求N到1的最短距离,以N为源点,用dijkstra即可。

坑点:要注意输入的路标间可能会是0,那么如果一开始各路距离初始化为0,就会出错,所以要先把各路距离初始化为无穷大。

代码:

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#define min(x,y) x<y?x:y;
using namespace std;
const int INF=1000000;
int map[1011][1011]={0};
int dis[1011]={0};
bool used[1011];
int N;
int fin()
{   
    //找到最小的并判断是否全部使用过 
    int k=-1;
    for(int i=1;i<N;i++)
    {
        if(!used[i]&&(k==-1||dis[k]>=dis[i]))
        {
            k=i;
        }
    }
    return k;
}
int main()
{
    int T;
    scanf("%d%d",&T,&N);
    for(int i=1;i<=N;i++)
    {
        for(int j=1;j<=N;j++)
        {
            map[i][j]=INF;
        }
    }
    for(int i=0;i<T;i++)
    {
        int a,b,c;
        scanf("%d %d %d",&a,&b,&c);
        if(a!=b)
        map[a][b]=map[b][a]=min(map[a][b],c);
    }
    for(int i=1;i<=N;i++)
        dis[i]=INF;
    for(int i=1;i<N;i++)
    {
        if(map[N][i]!=INF)
        dis[i]=map[N][i];
    }
​
    int num;
    while((num=fin())!=-1)
    {
        used[num]=true;
        for(int i=1;i<N;i++)
        {
            if(map[num][i]!=INF)
            {
                dis[i]=min(dis[i],dis[num]+map[num][i]);
            }
        }
    }
    printf("%d\n",dis[1]);
    return 0;
}
​
 

 

posted on 2020-01-28 16:38  Aminers  阅读(194)  评论(0编辑  收藏  举报

导航