您的位置:首页 > 其它

POJ-Til the Cows Come Home

2017-02-22 20:06 141 查看
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.

首先以后要多做英文题了,竞赛都是英文题,现在不靠翻译根本做不成,自己应该多锻炼一下

这道题是经典的最短路问题

本来想用Floyd-warshall的

但是那个复杂度为N的三次方,可能过不了

那么就选择时间复杂度更小一点的 Dijkstra

啊哈!算法上面介绍的很清楚,很好的一本书,抽空把前面的都补一补

我简单总结一下

这其实也非常类似于动规,不断的更新最优解

找到离点1最近的点,然后往推测后面的最短距离

这个点找过了下次就不考虑这个点了

下面直接上AC代码

#include<stdio.h>
#include<string.h>
int map[2005][2005];//建图
int dis[1005],book[1005];
int main()
{
int t,n,intf=99999999;
int min,l;
while(scanf("%d%d",&t,&n)!=EOF)
{
for(int i=1; i<=n; i++) //初始化
{
for(int j=1; j<=n; j++)
{
if(i==j)
{
map[i][j]=0;
}
else
{
map[i][j]=intf;
}
}
}
while(t--) //输入直接建图
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if(c<=map[a][b]) //因为给你可能不止一条路,选出一条最短的!
{
map[a][b]=map[b][a]=c;
}
}
for(int i=1; i<=n; i++)
{
dis[i]=map[1][i]; //初始化为各点到1的距离
}
memset(book,0,sizeof(book));
book[1]=1;
for(int i=1; i<=n-1; i++) //算法核心部分
{
min=intf;
for(int h=1; h<=n; h++) //找出离当前点最近的
{
if(book[h]==0&&dis[h]<min)
{
l=h;
min=dis[h];
//printf("%d\n",l); //测试数据
}
}
book[l]=1;
for(int j=1; j<=n; j++) //表示第几个点
{
if(dis[j]>dis[l]+map[l][j])
{
dis[j]=dis[l]+map[l][j];
}
}
/*for(int k=1; k<=n; k++) //测试数据
{
printf("%d ",dis[k]);
}
printf("\n");*/
}
printf("%d\n",dis
);
}
return 0;
}

如果自己写你就会发现一个问题
而这个问题我找了一天,那就是题目可能两点间不止一天路

第一次给你  1  2  20

第二次给你  1  2  30

输入的时候如果没有筛选那么  30 会把20覆盖,那么后面的再正确也出不来正确答案

就如这组数据

6 5
1 2 20

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


输入后看看结果还是不是90了  如果变成100了那就是输入的时候没有筛选

总结;

这道题自己还是不够细心,没有想到会要筛选,导致自己WA了两天,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Dijkstra-最短路