题目:
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.
* 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.
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100Sample Output
90Hint
There are five landmarks.
OUTPUT DETAILS:
Bessie can get home by following trails 4, 3, 2, and 1.
题意:
给出一些点之间的权值,求出1号结点到n号节点的最短路径(双向)
分析:
Bellman-Ford算法,判定时多加一个,表示双向就可以了
代码:
#include<stdio.h>
#include<string.h>
using namespace std;
#define inf 0x3f3f3f3f
int dis[2222],u[2222],v[2222],w[2222];
int main()
{
int i,j,n,m;
scanf("%d %d",&m,&n);
for(i=1;i<=m;i++)
scanf("%d %d %d",&u[i],&v[i],&w[i]);
memset(dis,inf,sizeof(dis));
dis[1]=0;
for(i=1;i<=n-1;i++)
{
int check=0;
for(j=1;j<=m;j++)
{
if(dis[v[j]]>dis[u[j]]+w[j])
{
dis[v[j]]=dis[u[j]]+w[j];
check=1;
}
if(dis[u[j]]>dis[v[j]]+w[j])
{
dis[u[j]]=dis[v[j]]+w[j];
check=1;
}
}
if(check==0)
break;
}
printf("%d",dis[n]);
return 0;
}