Problem Description
There are n pointson the plane, Pi(xi, yi)(1 <= i <= n), and xi < xj (i<j). You beginat P1 and visit all points then back to P1. But there is a constraint:
Before you reach the rightmost point Pn, you can only visit the points thosehave the bigger x-coordinate value. For example, you are at Pi now, then youcan only visit Pj(j > i). When you reach Pn, the rule is changed, from nowon you can only visit the points those have the smaller x-coordinate value thanthe point you are in now, for example, you are at Pi now, then you can onlyvisit Pj(j < i). And in the end you back to P1 and the tour is over.
You should visit all points in this tour and you can visit every point onlyonce.
Input
The input consistsof multiple test cases. Each case begins with a line containing a positiveinteger n(2 <= n <= 200), means the number of points. Then following nlines each containing two positive integers Pi(xi, yi), indicating thecoordinate of the i-th point in the plane.
Output
For each testcase, output one line containing the shortest path to visit all the points withthe rule mentioned above.The answer should accurate up to 2 decimal places.
Sample Input
3
1 1
2 3
3 1
Sample Output
6.47
题目大意:有n个点,告诉每个点的坐标。先从p1到pn,pi到pj必须保证i<j。再从pn到p1,pi到pj必须保证i>j,同时,来回之后必须保证每个点到且仅到一次。求最短路程。
对于题目来说,可以看做是两条从1出发到n的路。每当一条路选定了走法,另一条路的走法就是唯一的了。
两条路径分别为A和B,且起点都是点1,方向严格向右
1、A[i]表示路径A的一种状态,起点为点1,终点为点i,方向严格向右,1<=i<=n
2、B[j]表示路径B的一种状态,起点为点1,终点为点i,方向严格向右,1<=j<=n
3、dist[i][j]为点i与点j之间的距离
4、dp[i][j]为满足以下条件的A[i]和B[j]的路径和的最小长度:
a)A[i]和B[j]包含了所有的1-max(i,j)中的点;
b)A[i]和B[j]中没有重复了点(除了点1,或i=j时的点i)
经过以上定义,题目可以化简为求dp[n][n]的值。
dp[i][j]的意义即是A走到i点,B走到j点时的最短路程
min(dp[i][k]+dist[k][j])(1<=k<i) j=i+1;
dp[i][j] =
dp[i][j-1]+dist[j][j-1] j>i+1;
dp[i][i] = dp[i][i-1]+dist[i][i-1];
#include <iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<vector> #include<algorithm> #include<cmath> using namespace std; typedef struct NODE { int x ,y; }; double dist[210][210] ,dp[210][210]; NODE nodes[210]; int n; double dis(int a ,int b) { return sqrt((double)(nodes[a].y - nodes[b].y) * (nodes[a].y - nodes[b].y) + (nodes[a].x - nodes[b].x) * (nodes[a].x - nodes[b].x)); } int main() { while(~scanf("%d",&n)) { //计算两点间距离 for(int i = 1;i<=n;i++) { scanf("%d%d",&nodes[i].x,&nodes[i].y); for(int j = 1;j<i;j++) { dist[i][j] = dist[j][i] = dis(i,j); } } for(int i = 1;i<=n;i++) { for(int j = 1;j<=i;j++) { dp[i][j] = dp[j][i] = 999999999; } } dp[2][1] = dp[1][2] = dist[1][2]; for(int j = 3;j<=n;j++) { dp[j][1] = dp[1][j] = dp[1][j-1] + dist[j-1][j]; } for(int i = 2;i<=n;i++) { double ans = 99999999; for(int k = 1;k<i;k++) { if(ans > dp[i][k] + dist[k][i+1]) { ans = dp[i][k] + dist[k][i+1]; } } dp[i+1][i] = dp[i][i+1] = ans; for(int j = i + 2;j<=n;j++) { dp[j][i] = dp[i][j] = dp[i][j-1] + dist[j-1][j]; } } dp[n][n] = dp[n][n-1] + dist[n-1][n]; printf("%.2lf\n",dp[n][n]); } return 0; }