双调欧几里得旅行商问题(TSPhdu2224)

时间:2022-12-10 11:58:33

http://acm.hdu.edu.cn/showproblem.php?pid=2224

The shortest path

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 772    Accepted Submission(s): 400
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.

题意:平面上n个点,确定一条连接各点的最短闭合旅程。这个解的一般形式为NP的(在多项式时间内可以求出)

建议通过只考虑双调旅程(bitonictour)来简化问题,这种旅程即为从最左点开始,严格地从左到右直至最右点,然后严格地从右到左直至出发点。每个点都要走一次,且每个点只能走一次,求最短路径;

设dp[i][j]代表起始点到i的距离+起始点到j的距离,中间没有交叉点,且没有遗漏点(dp[i][j]=dp[j][i]);

当i<j-1的时候,dp[i][j]是从dp[i][j-1]传递过去的,即dp[i][j]=dp[i][j-1]+dis[j-1][j];

当i=j-1的时候,dp[i][j]是由dp[i][k]+dis[k][j]得到的,即dp[i][j]=min(dp[i][j],dp[i][k]+dis[k][j]);
程序:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include"stdio.h"
#include"string.h"
#include"iostream"
#include"map"
#include"string"
#include"queue"
#include"stdlib.h"
#include"algorithm"
#include"math.h"
#define M 222
#define eps 1e-10
#define inf 100000000000000
#define mod 1000000000
#define INF 1000000000
using namespace std;
struct node
{
double x,y;
}p[M];
double dp[M][M],dis[M][M];
double min(double a,double b)
{
return a<b?a:b;
}
double Len(node a,node b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int cmp(node a,node b)
{
return a.x<b.x;
}
int main()
{
int n,i,j;
while(scanf("%d",&n)!=-1)
{
for(i=0;i<n;i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
sort(p,p+n,cmp);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
dis[i][j]=Len(p[i],p[j]);
dp[0][1]=dis[0][1];
for(j=2;j<n;j++)
{
for(i=0;i<j-1;i++)
dp[i][j]=dp[i][j-1]+dis[j-1][j];
dp[j-1][j]=inf;
for(i=0;i<j-1;i++)
dp[j-1][j]=min(dp[j-1][j],dp[i][j-1]+dis[i][j]);
}
dp[n-1][n-1]=dp[n-2][n-1]+dis[n-2][n-1];
printf("%.2lf\n",dp[n-1][n-1]);
}
}