今天早上看了一上午,总算是明白了一点最短路,大概思路应该是这样,我拿一道板子题来说:
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.
题的大意就是求第一个到第T个村子的最短路径, 这里需要用到最短路的思想(迪杰斯特拉算法)。
首先需要建一个二维数组,用来存两个村庄的长度,用下标表示村庄的编号。
然后建两个一维数组,一个用来存从第一个村庄到下标的村庄的最短路径,一个用来标记是否已经求出第一个村庄到该村庄的最短路径。
语言描述可能不怎么清楚,直接贴代码了:
#include<iostream>
#include<cstdio>
#define max 999999999
using namespace std;
int map[2010][2010],dis[2010],vis[2010];
int N,T;
int a,b,c;
void dijk(){
int k=0,mini;//k为标记数组的下标,mini为保存到下标村庄最短路径的参数
for(int i=1;i<T;i++)//此循环先找出第一个村庄可以到那些村庄
dis[i]=map[1][i];
for(int i=1;i<=N;i++){//遍历所有村庄
mini=max;
for(int j=1;j<=N;j++){
if(!vis[j]&&dis[j]<mini){//如果村庄没有被标记并且存在更优解
mini=dis[j];
k=j;//保存下标
}
}
vis[k]=1;//标记该村庄
for(int j=1;j<=N;j++){
if(dis[j]>dis[k]+map[k][j])
dis[j]=dis[k]+map[k][j];
}
}
}
int main(){
while(~scanf("%d%d",&T,&N)){//T是几条路,N是几个村庄;
for(int i=0;i<=N;i++){
for(int j=0;j<=N;j++)
map[i][j]=max;//先初始化为一个近似无穷的数,方便之后比较
map[i][i]=0;//把自己到自己的路标记成0
vis[i]=0;//标记清零
dis[i]=max;//最短距离初始化为无穷大
}
for(int i=1;i<=T;i++){
scanf("%d%d%d",&a,&b,&c);
if(map[a][b]>c)
map[a][b]=map[b][a]=c;//把来回的路都赋值为c
}
dijk();//进入函数(迪杰斯特拉算法)
printf("%d\n",dis[N]);
}
return 0;
}
大致就是这样。