来自:[kuangbin带你飞系列4]最短路 专题
标签:最短路径dijk
思路:需要考虑两地标之间可能存在多条路径
Til the Cows Come Home
TimeLimit:1000MS MemoryLimit:65536K
64-bit integer IO format:%lld
Problem Description
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.
SampleInput5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100
SampleOutput
90
问题描述
贝西在田里,想在农夫约翰叫醒她早上挤奶之前回到谷仓尽可能多地睡一觉。贝西需要她的美梦,所以她想尽快回来。
农场主约翰的田里有n(2<=n<=1000)个地标,唯一编号为1…n。地标1是谷仓;贝西整天站在其中的苹果树小树林是地标n。奶牛在田里行走时使用地标间不同长度的T(1<=t<=2000)双向牛道。贝西对自己的导航能力没有信心,所以一旦开始,她总是沿着一条从开始到结束的路线行进。
根据地标之间的轨迹,确定贝西返回谷仓必须走的最小距离。这样的路线一定存在。
输入
*第1行:两个整数:t和n
*第2.t+1行:每行将一条轨迹描述为三个空格分隔的整数。前两个整数是两条轨迹之间的标志。第三个整数是跟踪的长度,范围为1…100。
输出
*第1行:一个整数,贝西从地标N到地标1的最小距离。
#include<iostream>
#include<cstdio>
#define IN INT_MAX
using namespace std;
int e[1002][1002],dis[1002],book[1002];
int main()
{
int i,j,t,n,p,q,l,u,v,min;
scanf("%d%d",&t,&n);
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
{
if(i==j)
e[i][j]=0;
else
e[i][j]=IN;
}
}
//矩阵初始化
for(i=0;i<t;i++)
{
scanf("%d%d%d",&p,&q,&l);
if(e[p][q]!=IN)
{
if(l<e[p][q])
{
e[p][q]=l;
e[q][p]=l;
}
}
else
{
e[p][q]=l;
e[q][p]=l;
}
}
// for(i=1;i<=n;i++)
// {
// for(j=1;j<=n;j++)
// {
// if(e[i][j]==IN)
// printf(" * ");
// else
// printf("%3d ",e[i][j]);
// }
// printf("\n");
// }
// printf("\n");
//输入
for(i=1;i<=n;i++)
{
dis[i]=e[1][i];
book[i]=0;
}
book[1]=1;
//初始化dis book
for(i=1;i<=n;i++)
{
min=IN;
//
// for(j=1;j<=n;j++)
// {
// if(dis[j]==IN)
// printf(" * ");
// else
// printf("%3d ",dis[j]);
// }
// printf("\n");
for(j=1;j<=n;j++)
{
if(book[j]==0&&dis[j]<min)
{
min=dis[j];
u=j;
}
}
book[u]=1;
for(v=1;v<=n;v++)
{
if(e[u][v]<IN)
{
if(dis[v]>dis[u]+e[u][v])
dis[v]=dis[u]+e[u][v];
}
}
}
//Dijkstra
printf("%d\n",dis[n]);
return 0;
}