P1339[USACO09OCT]HeatWave
题意概述
The good folks in Texas are having a heatwave this summer. Their Texas Longhorn cows make for good eating but are not so adept at creating creamy delicious dairy products. Farmer John is leading the charge to deliver plenty of ice cold nutritious milk to Texas so the Texans will not suffer the heat too much.
FJ has studied the routes that can be used to move milk from Wisconsin to Texas. These routes have a total of T (1 <= T <= 2,500) towns conveniently numbered 1..T along the way (including the starting and ending towns). Each town (except the source and destination towns) is connected to at least two other towns by bidirectional roads that have some cost of traversal (owing to gasoline consumption, tolls, etc.). Consider this map of seven towns; town 5 is the
source of the milk and town 4 is its destination (bracketed integers represent costs to traverse the route):1
2
3
4
5
6
7
8
9 [1]----1---[3]-
/ \
[3]---6---[4]---3--[3]--4
/ / /|
5 --[3]-- --[2]- |
\ / / |
[5]---7---[2]--2---[3]---
| /
[1]------
Traversing 5-6-3-4 requires spending 3 (5->6) + 4 (6->3) + 3 (3->4) = 10 total expenses.
Given a map of all the C (1 <= C <= 6,200) connections (described as two endpoints R1i and R2i (1 <= R1i <= T; 1 <= R2i <= T) and costs (1 <= Ci <= 1,000), find the smallest total expense to traverse from the starting town Ts (1 <= Ts <= T) to the destination town Te (1 <= Te <= T).
INPUT & OUTPUT’s examples
Input’s eg #1
1 | 7 11 5 4 |
Output’s eg #1
1 | 7 |
样例说明
1 | 5->6->1->4 (3+1+3) |
分析
比较简单的一道图论基础题对吧。
题意非常明显,就是在一个无向图中求两个定点之间的最短路。
那么,我们就可以使用SPFA算法来做。
这里,我们定义两个vector
不定长动态数组,一个是Map[i][j]
存储这张地图,另一个是value[i][j]
表示从i
到j
的路径的长度。
初始化之后,我们就可以开始求解了。定义一个队列queue<int>Q
来作为求解队列。
首先,开始求解之前,我们假设所有的点距离都为inf
,这时所有的点也都没有被访问过。
然后我们将起点入队,然后开始查找。当查找队列不为空时,我们取出队头first
,将它的标记解除。
然后枚举与它相连的所有点i
,如果选择first->i
为其中一条路径,使得起点到i
的距离更短,那么更新dist
数组。
如果Map[first][i]
,不在队列里(即被松弛),那么把他加入队列,打上标记。
如此循环下去,答案就是dist[T]
。
代码
1 | /* Headers */ |