# poj-Til the Cows Come Home（Bellman-Ford）

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

Bellman-Ford  算法与Dijkstra  的思路是一样的

#include<stdio.h>
#include<string.h>
int u[2005],v[2005],w[2005];
int dis[1005];
int main()
{
int n,t,flag;
int inf=99999999;
while(scanf("%d%d",&t,&n)!=EOF)    //t是边，n是点
{
for(int i=1;i<=t;i++)     //输入各条边的信息
{
scanf("%d%d%d",&u[i],&v[i],&w[i]);
}
for(int i=1;i<=n;i++)
{
dis[i]=inf;
}
dis[1]=0;
for(int i=1;i<=n-1;i++)
{
flag=1;
for(int j=1;j<=t;j++)
{
if(dis[v[j]]>dis[u[j]]+w[j])
{
dis[v[j]]=dis[u[j]]+w[j];
flag=0;
}
if(dis[u[j]]>dis[v[j]]+w[j])   //路是双向的，这是第二种情况
{
dis[u[j]]=dis[v[j]]+w[j];
flag=0;
}
}
if(flag==1)
{
break;
}
/*for(int k=1;k<=n;k++)  //测试代码
{
printf("%d ",dis[k]);
}
printf("\n");*/
}
printf("%d\n",dis[n]);
}
return 0;
}

原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/wjhshuai/article/details/56856907
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。