Til the Cows Come Home
Time Limit: 1000MS | Memory Limit: 65536K |
Total Submissions: 20550 | Accepted: 6864 |
题目链接:http://poj.org/problem?id=2387
Description
Bessie is out in the field andwants to get back to the barn to get as much sleep as possible before FarmerJohn wakes her for the morning milking. Bessie needs her beauty sleep, so shewants to get back as quickly as possible.
Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquelynumbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessiestands all day is landmark N. Cows travel in the field using T (1 <= T <=2000) bidirectional cow-trails of various lengths between the landmarks. Bessieis not confident of her navigation ability, so she always stays on a trail fromits start to its end once she starts it.
Given the trails between the landmarks, determine the minimum distance Bessiemust walk to get back to the barn. It is guaranteed that some such routeexists.
Input
* Line 1: Two integers: T andN
* 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. Thethird 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 landmark1.
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.
Source
解题思路:
这是一个典型的求单源最路径的题目,即求第一点到最后一点的最短距离,可以用Ballman-Ford算法来解决,Ballman-Ford算法主要思路是先将第一点到任意一点的最短距离设置为无穷大,将本身设置为0,然后在遍历每一条边(要注意的是建立图的时候是无向图,边的长度要乘以2),如果这条边的起点到第一点的距离不是无穷大,而且这条边的终点到第一点的距离大于这条边起点到这点的距离加上这条边的权值,那么就更新这条边终点到第一点的最小距离,要注意的是输入时是先输入边在输入点的
代码:
#include <iostream>
#include<cstdio>
#include<cstring>
#define MAX 400003
#define VALUE 999999
using namespace std;
struct edge
{//定义边
int from;
int to;
int cost;
};
int v,es;
int d[MAX];//某一点到任意一点的最短距离
edge e[2*MAX];
//建带权图
void createGraph()
{
int start,end,weight;
scanf("%d%d",&es,&v);
int i;
for(i=0;i<es;i++)
{
//无向图,边数等于2*e
scanf("%d%d%d",&start,&end,&weight);
e[i].from=start;
e[i].to=end;
e[i].cost=weight;
e[es+i].from=end;
e[es+i].to=start;
e[es+i].cost=weight;
}
}
//求第s个顶点到各个顶点的最短距离
void shortPath(int s)
{
int i;
//初始化s点到任意一点的距离达到最大
for(i=1;i<=v;i++)
{
d[i]=VALUE;
}
d[s]=0;//s到s本身的距离为0
while(true)
{
bool update=false;
for(int i=0;i<2*es;i++)
{//遍历每一条边
edge ed=e[i];
//s到ed.from这点的距离如果不是无穷大,并且s到ed.to的距离大于ed.from+ed.cost;
if(d[ed.from]!=VALUE && d[ed.to]>d[ed.from]+ed.cost)
{
//更新s到ed.to这点的距离
d[ed.to]=d[ed.from]+ed.cost;
update=true;
}
}
if(update==false)
break;//确保每条边都能更新到
}
printf("%d\n",d[v]);
}
int main()
{
createGraph();
shortPath(1);
return 0;
}