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 的思路是一样的
都是根据某一条件推断出部分最短路,然后不断的更新(动规思想)
然而不一样的就是~某一条件~前者是用边,后者用点
两个算法放一起再仔细比较一下
别的不再多说
有一个问题是
这个方法不用建图,也不用考虑重边(因为重边中长的根本无法更新最短路,有跟没有一样)
其次注意路是双向的,刚开始我写成单向了,WA了好一会
下面直接上代码了
#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;
}
还有就是其实我们可以对其进行优化
在实际操作中这种算法经常会在未达到n-1轮松弛钱就已经
计算出最短路,之前我们已经说过,n-1其实是最大值
因此可以添加一个变量check用来标记数组dis在本轮松弛中
是否发生了变化,如果没有发生变化,则可以提前跳出循环