Til the Cows Come Home
问题描述
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.
PS:这题中是有重边的
dijkstra
//A-Til the Cows Come Home
#include<stdio.h>
#define INF 1<<29
#define MAXV 1005
int t, n;
int map[MAXV][MAXV];
void dijkstra(){
int i, j, v, min;
int d[MAXV]; //储存当前点到其他点的距离
int vist[MAXV]; //vist[i]=0时,未访问; vist[i]=1时,已访问过
for(i=1; i<=n; i++){
vist[i]=0; //初始化
d[i]=map[1][i]; //储存起点到其他点的距离
}
for(i=1; i<=n; i++){
min=INF;
for(j=1; j<=n; j++){
if(!vist[j]&&d[j]<min){
v=j; //距离当前点最近的点
min=d[j];
}
}
vist[v]=1; //标记之
for(j=1; j<=n; j++){
//寻找是否存在中转点,使路径最短
if(!vist[j]&&d[j]>d[v]+map[v][j]){
d[j]=d[v]+map[v][j];
}
}
}
//数组d最终存放的是起点到其他点的最短路径长度
printf("%d\n", d[n]);
}
int main(void){
int i, j, a, b, c;
while(~scanf("%d %d", &t, &n)){//t条路,n个点
for(i=1; i<=n; i++){
for(j=1; j<=n; j++){
//init()
if(i==j){
map[i][j]=0;
}else{
map[i][j]=map[j][i]=INF;
}
}
}
for(i=1; i<=t; i++){
scanf("%d %d %d", &a, &b, &c); //输入时,是从1开始计数的
//去重边,保留最小权边
if(map[a][b]>c){
map[a][b]=map[b][a]=c;
}
}
dijkstra();
}
return 0;
}
代码参考至http://blog.csdn.net/wangjian8006
- 1605集训计划第十五天任务
- 按时完成