题意:从1走到n,再从n走回1,除1和n外,每个点只走一次。去的时候,点走升序;回的时候走降序。问走的最短距离?
题解:我们可以视为从1走到n,走两次,每次延标号升序列走,且不重复走点。
dp[i][j]表示从1出发,走双线程,走到j点(默认j>i,已走完1到j的所有点)的最小消耗
则 dp[i][j+1] = min(dp[i],[j+1] , dp[i][j]+dis(j,j+1) )
dp[j][j+1] = min(dp[i],[j+1] , dp[i][j]+dis(i,j+1) )
循环更新即可
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 530 +5;
const double inf = 1e16;
typedef long long ll;
struct point
{
double x,y;
}p[N];
double dis(int c,int d)
{
point a = p[c], b = p[d];
return sqrt( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
}
double dp[N][N];
int t,n;
int main()
{
scanf("%d",&t);
double ans;
while(t--){
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) dp[i][j] = inf;
dp[1][1] = 0;
dp[1][2] = dis(1,2);
for(int i=1;i<n;i++)
for(int j=i+1;j<n;j++){
dp[i][j+1] = min(dp[i][j+1],dp[i][j]+dis(j,j+1));
dp[j][j+1] = min(dp[j][j+1],dp[i][j]+dis(i,j+1));
}
ans = inf;
for(int i=1;i<n;i++)
ans = min(dp[i][n]+dis(i,n),ans);
printf("%.8f\n",ans);
}
return 0;
}