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 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. 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
题意:对于给出的点从左边走到右边但是还要从右边走到出发点,路线最短还要遍历完点。
参考资料:http://blog.sina.com.cn/s/blog_51cea4040100gkcq.html
思路:dp[i][j]表示走得快的人走到i, 走得慢的人走到j, 时的最小路程, 从左到右对于每一个点,要么给走得快的人,要么给走得慢的人, dp[i][j]=INF;
dp[i+1][i]=min{dp[i+1][i], dp[i][j]+dis[j][i+1]};
dp[i+1][j]=min{dp[i+1][j], dp[i][j]+dis[i][i+1]};
代码如下:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<math.h>
using namespace std;
#define INF 0xfffffff
int dp[10005][105], a[10005];
struct point
{
int x, y;
}p[105];
double get_dis(point xx, point yy)
{
return sqrt(1.0*(xx.x-yy.x)*(xx.x-yy.x)+1.0*(xx.y-yy.y)*(xx.y-yy.y));
}
double min1(double x1, double y1)
{
if(x1<y1)
return x1;
return y1;
}
int main()
{
int i, j, k, n;
double dp[105][105],dis[105][105];
while(scanf("%d", &n)!=EOF)
{
for(i=1; i<=n; i++)
scanf("%d%d", &p[i].x, &p[i].y);
memset(dis, 0, sizeof(dis));
for(i=1; i<n; i++)
for(j=i+1; j<=n; j++)
{
dis[j][i]=get_dis(p[i], p[j]);
dis[i][j]=dis[j][i];
}
for(i=0; i<=100; i++)
for(j=0; j<=100; j++)
dp[i][j]=INF*1.0;
dp[2][1]= dis[2][1];
for(i=1; i<=n; i++)
for(j=1; j<i; j++)
{
dp[i+1][j]=min1(dp[i+1][j], dp[i][j]+dis[i][i+1]);
dp[i+1][i]=min1(dp[i+1][i], dp[i][j]+dis[i+1][j]);
}
double minnum=INF*1.0;
for(i=1; i<n; i++)
minnum=min1(minnum, dp[n][i]+dis[i][n]);
printf("%.2lf\n", minnum);
}
}