POJ 2677 双调欧几里得旅行商问题

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 = <xiyi > . 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 ycoordinates. 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个点,要求从最左端点严格向右走到最右端点,再从最右端点走回来,途中必须经过所有点(保证每个点横坐标不同),求最短路。

解题思路:

双调欧几里得旅行商问题,dp。将点按横坐标从小到大排序,dp[i][j]表示从j向左走到1,再从1走到i的最短路(i

给出转移方程:

dp[i][j]=dp[i][j-1]+dist(j-1,j)    (i<=j-2);

dp[j-1][j]=min(dp[j-1][j],dp[i][j-1]+dist(i,j))   (i<=j-2);

按此方式更新不会丢失最优解(每次只把j纳入集合而不考虑j+1,j+2...)

最终得到dp[n][n]=dp[n-1][n]+dist(n-1,n);

代码:

#include
#include
#include
#include
using namespace std;
const double INF=1.0*9999999;
struct Node
{
        int x,y;
};
Node a[1005];
double dp[1005][1005];
int n;
double dist(int i,int j)
{
        return sqrt((a[i].x-a[j].x)*(a[i].x-a[j].x)+(a[i].y-a[j].y)*(a[i].y-a[j].y));
}
int main()
{
        while(~scanf("%d",&n))
        {
                for(int i=1;i<=n;i++)
                        scanf("%d%d",&a[i].x,&a[i].y);
                memset(dp,INF,sizeof dp);
                dp[1][2]=dist(1,2);
                for(int j=3;j<=n;j++)
                {
                        for(int i=1;i<=j-2;i++)
                                dp[i][j]=dp[i][j-1]+dist(j-1,j);
                        dp[j-1][j]=INF;
                        for(int i=1;i<=j-2;i++)
                                dp[j-1][j]=min(dp[i][j-1]+dist(i,j),dp[j-1][j]);
                }
                dp[n][n]=dp[n-1][n]+dist(n-1,n);
                cout<


 
  




你可能感兴趣的:(DP)