Problem Description
John Doe, a skilled pilot, enjoys traveling. While on vacation, he rents a small plane and starts visiting beautiful places.
To save money, John must determine the shortest closed tour that connects his destinations.
Each destination is represented by a point in the plane p i = ( x i , y i ) p_{i} = (x_{i}, y_{i}) pi=(xi,yi). John uses the following strategy:
he starts from the leftmost point, then he goes strictly left to right to the rightmost point, and then he goes strictly
right back to the starting point. It is known that the points have distinct x-coordinates.
Write a program that, given a set of n points in the plane, computes the shortest closed tour that connects the
points according to John’s strategy.
Input
The program input is from a text file. Each data set in the file stands for a particular set of points. For
each set of points the data set contains the number of points, and the point coordinates in ascending
order of the x coordinate. White spaces can occur freely in input. The input data are correct.
Output
For each set of data, your program should print the result to the standard output from the beginning
of a line. The tour length, a floating-point number with two fractional digits, represents the result.
Note: An input/output sample is in the table below. Here there are two data sets. The first one
contains 3 points specified by their x and y coordinates. The second point, for example, has the x
coordinate 2, and the y coordinate 3. The result for each data set is the tour length, (6.47 for the first
data set in the given example).
Sample Input
3
1 1
2 3
3 1
4
1 1
2 3
3 1
4 2
Sample Output
6.47
7.89
\newline
\newline
\newline
思路1
这题自己做得有点懵懂,很多细节都感觉没考虑清楚,有点云里雾里的感觉。但是提交上去居然AC了,没想到啊。。。
先说说我自己做这个题的时候的想法,因为每个点都需要被遍历,或者是在从左到右,或者从右到左。有点像0 - 1背包问题,只不过这里有两个背包,如果第一个背包不取当前的点,那么第二个背包必须取。所以一开始想构造第一个背包从左到右遍历到前 i 个点的时候,最小的距离是多少这样的状态。但是发现状态转移方程很难写,因为不知道前面一个点是啥。。。OK,那我改变一下,定义状态:第一个背包从左往右遍历到第 i 个点且第 i 个点必须取的时候,最小的距离。这样就解决了刚刚 “不知道前一个点是啥” 这个问题。但是现在还是很难写状态转移方程,因为不知道第二个背包里面有啥东西,虽然我知道第二个背包和第一个背包互补,但是具体怎么反映到程序上是个问题。
这儿纠结了一会儿,我想到干脆用一个二维变量 ( i , j ) (i, j) (i,j) 表示第一个背包最后一个取的点为 i,第二个背包最后一个取的点为 j
这样如果有 i > j i > j i>j,那么再分两种情况,如果 j < i − 1 j < i - 1 j<i−1,那么 i − 1 i - 1 i−1 这个点必然是属于第一个背包,那么必然有:
d p [ i ] [ j ] = d p [ i − 1 ] [ j ] + d i s t ( i − 1 , i ) dp[i][j] = dp[i - 1][j] + dist(i - 1, i) dp[i][j]=dp[i−1][j]+dist(i−1,i)
如果 j = = i − 1 j == i - 1 j==i−1,那么 ( i , j ) (i, j) (i,j) 可以由 ( k , j ) , 0 ≤ k < j (k, j), \space 0 \le k < j (k,j