最短路径
一、最短路径
单源最短路(求一个点到其他所有点的最小距离)
通常用Dijkstra算法解决,前提是不存在负环。O(n^2)
常规步骤:
初始化距离 dis[1] = 0,dis[i] = + ∞ (dis数组表示起点到i点的距离)for循环 1~n循环n次 ,找到不在s中的距离起点最近的点,赋给t,s是当前到起点距离最短的点,把t加到s中去,如果七点到其他点的距离大于到t点的距离,用t更新,每次循环确定一个点到起点的距离,n次就能找完所有点。
多源汇最短路(求任意两点间的最短距离)
通常用Floyd算法解决,也不能存在负环。O(n^3)
常规步骤:
设置数组 d[k,i,j]:从点 i 只经过1~k这些中间点到达点 j 的最短距离,那么就有:d[k,i,j] = d[k-1,i,k] + d[k-1,k,j] 。
我们可以把点i到j的方式归为两类1. 从i 直接到 j;2. 从i 经过若干个点 到 j;循环判断选择较短的那条路。
二、例题
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