紫书上面已经描述得很清楚了,模拟成两个人同时从起始点出发,然后在终点相遇即可,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;
int n;
struct node{
int x, y;
};
double length[1000][1000];
double dp[1000][1000];
int main(){
while (cin >> n){
vector<node> v;
for (int i = 0; i < n; i++){
node temp;
cin >> temp.x >> temp.y;
v.push_back(temp);
}
for (int i = 0; i < n; i++){
for (int j = 0; j < i; j++){
length[i][j] = sqrt((v[i].x-v[j].x)*(v[i].x-v[j].x)+(v[i].y-v[j].y)*(v[i].y-v[j].y));
}
}
for (int j = 0; j < n - 1; j++){
dp[n - 1][j] =length[n-1][j];
}
for (int i = n - 2; i >= 0; i--){
for (int j = 0; j < i; j++){
dp[i][j] = min(dp[i+1][j]+length[i+1][i],dp[i+1][i]+length[i+1][j]);
}
}
cout<<fixed<<setprecision(2)<< dp[1][0]+length[1][0] << endl;
}
return 0;
}