uva - 1347 Tour ( 动态规划 + 递归 )

Tour


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



一道动态规划的题目,题意大概是要把给出的几个点全部走一遍,走一个圈回到起点,要求走的距离最短。

这题的思路可以转化成两人同时从起点出发,朝两个方向向终点前进,且不会走重复的点。如何判断这个点是否已经走过的了是一个难点。我的方法是递归函数,每次输入的是i和j,表示最前面的两个点(i表示前面的点,j表示后面的点),每次如果的是i向前走一个点 函数(i+1,i),因为j点走到了i的前面,i反而成了后面的点。同理j向前走之后函数的表达式变为 函数(i+1,j)。并且建立一个二维数组dp[ ][ ],来储存已经走了的距离。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
struct node      
{
    int x,y;
}v[1010];                   //用来储存各个点。

double dp[1010][1010];
int n;
double dd(node a,node b)    //用于计算距离的函数
{
    return sqrt((a.y-b.y)*(a.y-b.y)+(a.x-b.x)*(a.x-b.x));
}

double dg(int i,int j)      //实现上面解释中的函数()功能
{
    if(i == n-1)
        return dd(v[n],v[n-1])+dd(v[j],v[n]);
    if(dp[i][j]>0) return dp[i][j];
    return dp[i][j] = min(dg(i+1,j)+dd(v[i],v[i+1]),dg(i+1,i)+dd(v[j],v[i+1]));

}

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("out.txt","w",stdout);

    while(cin>>n&&n)
    {
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
            cin>>v[i].x>>v[i].y;
        }
        for(int i=1;i<n-1;i++)
            dp[n-1][i]=dd(v[n],v[n-1])+dd(v[i],v[n]);   //初始化每个dp[][]的值,来减小后续的运算量
        double ans=dg(1,1);

        printf("%.2lf\n",ans);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/j1nab1n9/article/details/77334436
今日推荐