这是一道简单的最短路题目,用迪杰斯特拉算法就可解决。
Description
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
* 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
Sample Input
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100
Sample Output
90
#include<iostream>
#include<cstring>
using namespace std;
int INF = 0xfffffff;
int v[1001];
int d,b;
int dis[1001];
int map[101][101];
int Min(int a,int b)
{
return a>b?b:a;
}
int dij()
{
//memset(map,0,sizeof(map));
//for(int i=1;i<=d;i++)
//{
// dis[i]=INF;
// v[i]=false;
//}
dis[1]=0;
for(int i=1;i<=d;i++)
{
int mark;
int mindis=INF;
for(int j=1;j<=d;j++)
{
if(!v[j]&&dis[j]<mindis)
{
mark=j;
mindis=dis[j];
}
}
v[mark]=true;
for(int j=1;j<=d;j++)
{
if(!v[j])
dis[j]=Min(dis[mark]+map[mark][j],dis[j]);
}
}
for(int i=1;i<=d;i++)
cout<<i<<' '<<dis[i]<<endl;
return 0;
}
int main()
{
cin>>d>>b;
for(int i=1;i<=d;i++)
for(int j=1;j<=d;j++)
{
dis[i]=INF;
v[i]=false;
map[i][j]=map[j][i]=INF;
}
for(int i=1;i<=b;i++)
{
int x,y,z;
cin>>x>>y>>z;
map[x][y]=z;
map[y][x]=z;
}
dij();
system("pause");
return 0;
}