1347 - Tour

来源:互联网 发布:淘宝 女童羽绒服 编辑:程序博客网 时间:2024/06/10 01:56

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 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

我有话说:
这道题的大意是有n个点,按x坐标排序给出。要求从1出发再回到起点。要求走过所有的点且路程最小。两个点之间的距离即他们的欧几里德距离。
因为要考虑来回的路程最小。如果先从左到右枚举,再回来不利于状态的转移。所以我们定义d(i,j)为两个人一起从1出发其中一个在i,一个在j,还需要 走的路程。为了保证每一个点都走过去,不漏解,我们定义i > j,d(i,j)为前1到max(i,j)序号的点全部走过,当前位置一个在i,一个在j且每次只允许一个人只能走到i+1,即状态d(i,j)只能转移到d(i+1,j)或d(i+1,i)。
转移方程: d[i][j]=min(dist[i][i+1]+d[i+1][j],dist[j][i+1]+d[i+1][i]);
边界:d[n-1][j]=dist[n-1][n]+dist[j][n];
最后输出:d[2][1]+dist[1][2]。因为第一步任何一个人都只能走到2.

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <cmath>using namespace std;const int maxn=50+5;double x[maxn],y[maxn],d[maxn][maxn],dist[maxn][maxn];int main(){    int n;    while(scanf("%d",&n)==1)    {       for(int i=1;i<=n;i++)       {           scanf("%lf%lf",&x[i],&y[i]);       }       for(int i=1;i<=n;i++)          for(int j=1;j<=n;j++)             dist[i][j] = sqrt((x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j]));        for(int i=n-1;i>=2;i--)        {            for(int j=1;j<i;j++)            {                if(i==n-1)d[i][j]=dist[i][n]+dist[j][n];                else d[i][j]=min(dist[i][i+1]+d[i+1][j],dist[j][i+1]+d[i+1][i]);            }        }        printf("%.2lf\n",d[2][1]+dist[1][2]);    }    return 0;}
0 0
原创粉丝点击