The shortest path
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1669 Accepted Submission(s): 866
Problem Description
There are n points on the plane, Pi(xi, yi)(1 <= i <= n), and xi < xj (i<j). You begin at 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 those have the bigger x-coordinate value. For example, you are at Pi now, then you can only visit Pj(j > i). When you reach Pn, the rule is changed, from now on you can only visit the points those have the smaller x-coordinate value than the point you are in now, for example, you are at Pi now, then you can only visit 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 only once.
Input
The input consists of multiple test cases. Each case begins with a line containing a positive integer n(2 <= n <= 200), means the number of points. Then following n lines each containing two positive integers Pi(xi, yi), indicating the coordinate of the i-th point in the plane.
Output
For each test case, output one line containing the shortest path to visit all the points with the 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
Hint: The way 1 - 3 - 2 - 1 makes the shortest path.
在最短路合集里看到的题目,结果想了好久觉得最短路不能实现
结果是TSP模板题,第一次接触这类题目,dp的思路如下:
dp[ i ][ j ]表示为从P1到Pi和从P1到Pj的最短路距离,两条路没有交点,并且两条路包含了小于等于 j 的所有点,而dp[ i ][ j ]=dp[ j ][ i ],那么dp[1][2]即为dis[1][2],那么在这种情况下只需要考虑 i <= j 的情况即可。
1.i < j - 1 :从 1 到 i 和从 1 到 j 的最短路的和即可表示为dp[ i ][ j - 1 ] + dis[ j - 1 ][ j ] ,即 dp[i][j] 是从 dp[i][j-1] 导出
2.i == j - 1 :此时的 dp[ j - 1 ][ j ] = min(dp[ j - 1 ][ j ], dp[ k ][ j ] + dis[ k ][ j - 1 ])
画个图意会一下就懂了
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define N 210
#define INF 0x3f3f3f3f
double dis[N][N];
double dp[N][N];
double x[N], y[N];
int main()
{
int n;
while(~scanf("%d", &n))
{
for(int i = 1; i <= n; i++)
{
scanf("%lf%lf", &x[i], &y[i]);
}
for(int i = 1; i < n; i++)
{
for(int j = i + 1; j <= n; j++)
{
dis[i][j] = dis[j][i] = sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
}
}
dp[1][2] = dp[2][1] = dis[1][2];
for(int j = 3; j <= n; j++)
{
for(int i = 1; i < j - 1; i++)
{
dp[i][j] = dp[i][j-1] + dis[j-1][j];
}
dp[j-1][j] = INF;
for(int k = 1; k < j - 1; k++)
{
dp[j-1][j] = min(dp[j-1][j], dp[k][j-1] + dis[k][j]);
}
}
dp[n][n] = dp[n-1][n] + dis[n-1][n];
printf("%.2lf\n", dp[n][n]);
}
return 0;
}