The shortest path HDU - 2224 双调欧几里得问题模板

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问题(Traveling Salesman Problem)又译为旅行推销员问题、货郎担问题,是数学领域中著名问题之一。假设有一个旅行商人要拜访n个城市,他必须选择所要走的路径,路径的限制是每个城市只能拜访一次,而且最后要回到原来出发的城市。路径的选择目标是要求得的路径路程为所有路径之中的最小值。

思路:

  1. 对n个点按x坐标的大小从小到大进行排序,我们用dp[ i ][ j ]表示其中一条路径从起点走到 i 点,另一条路径从起点走到 j 点时的最短距离(路径并不重叠),那么我们要求的答案存在dp[ n ][ n ]。我们很容易想到dp[ i ][ j ] == dp[ j ][ i ],因此我们只计算 j < = i 的情况。
  2. 分两种情况:①当 j < i - 1 时,这种情况下,dp[ i ][ j ]只能由dp[ i - 1 ][ j ]进行转移,因为路径要求严格从左至右,所以能到达i点的只能是点i -1。此时dp[ i ][ j ] = dp[ i - 1 ] [ j ] + dis[ i -1 ][ i ] ;②当 j = = i -1时,这种情况下到达i点一定不是从i - 1这个点到达的(因为路径不能重叠),则路径可分为一条路径从1到 i - 1 ,另一条路径从1到k,然后从k到 i ( k < i - 1 )。计算方程时应该这么算:dp[ i ][ i-1 ] = min ( dp[ i ][ i-1 ], dp[ i - 1 ][ k ] + dis[ k ][ i ])。
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm> 
using namespace std;
const int maxn=209;
const int inf=0x3f3f3f3f;
struct node{
	int x;
	int y;
}a[maxn];
bool cmp(node x,node y)
{
	if(x.x!=y.x)
		return x.x<y.x;
	else
	 	return x.y<y.y;
}
int n;
double dis[maxn][maxn],dp[maxn][maxn];
int main()
{
	while(~scanf("%d",&n))
	{
		double ans;
		for(int i=1;i<=n;i++)
			scanf("%d%d",&a[i].x,&a[i].y);
		sort(a+1,a+1+n,cmp);
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++)
				dis[i][j]=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));
		dp[2][1]=dis[2][1];
		for(int i=3;i<=n;i++)
		{
			for(int j=1;j<i-1;j++)
				dp[i][j]=dp[i-1][j]+dis[i-1][i];
			dp[i][i-1]=inf;
			for(int k=1;k<i-1;k++)
				dp[i][i-1]=min(dp[i][i-1],dp[i-1][k]+dis[k][i]); 
		}
		if(n==2) ans=dis[1][2];
		else ans=dp[n][n]=dp[n][n-1]+dis[n][n-1];
		printf("%.2lf\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/why932346109/article/details/89362158
今日推荐