题意是给你n个点,你需要从第一个到第n个点连一条折线,折线中间按顺序经过若干个点,并且折线外的点离这条折线的最近距离需要小于D。需要求这条折线的最小长度。
DP[i][j]表示到第i个点为止折线上有j条线段的最短长度,那么DP[k][j+1] = min (dp[k][j+1], dp[i][j]+distance (i, j)), 其中k>i,并且在线段ik之间的每个点都满足点到线段的距离小于等于D。
#include <bits/stdc++.h> using namespace std; #define maxn 111 #define INF 1e20 double dp[maxn][maxn]; int n; double x, y, d; double dis[maxn][maxn]; bool ok[maxn][maxn]; struct point { double x, y; point (double xx = 0, double yy = 0) : x(xx), y(yy) {} }p[maxn]; point operator + (point a, point b) { return point (a.x+b.x, a.y+b.y); } point operator - (point a, point b){ return point (a.x-b.x, a.y-b.y); } bool operator < (point a, point b){ return a.x < b.x || (a.x == b.x && a.y < b.y); } const double eps = 1e-10; int dcmp (double x) { if (fabs (x) < eps) return 0; else return x < 0 ? -1 : 1; } bool operator == (const point &a, const point &b) { return dcmp (a.x-b.x) == 0 && dcmp (a.y-b.y) == 0; } double Dot (point a, point b) { return a.x*b.x + a.y*b.y; } double Length (point a) { return sqrt (Dot (a, a)); } double Cross (point a, point b) { return a.x*b.y - a.y*b.x; } double DistanceToSegment (point p, point a, point b) { if (a == b) return Length (p-a); point v1 = b-a, v2 = p-a, v3 = p-b; if (dcmp (Dot (v1, v2)) < 0) return Length (v2); else if (dcmp (Dot (v1, v3)) > 0) return Length (v3); else return fabs (Cross (v1, v2)) / Length (v1); } double get_dis (int i, int j) { double x1 = p[i].x, y1 = p[i].y, x2 = p[j].x, y2 = p[j].y; return sqrt ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); } void legal () { for (int i = 1; i <= n; i++) { for (int j = i+1; j <= n; j++) { ok[i][j] = 1; for (int k = i+1; k < j; k++) { double dd = DistanceToSegment (p[k], p[i], p[j]); if (dd > d) { ok[i][j] = 0; break; } } } } } int main () { //freopen ("in", "r", stdin); while (cin >> n >> d && n+d) { for (int i = 1; i <= n; i++) { cin >> p[i].x >> p[i].y; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { dp[i][j] = INF; } } for (int i = 1; i <= n; i++) { for (int j = i+1; j <= n; j++) dis[i][j] = dis[j][i] = get_dis (i, j); } legal (); for (int i = 2; i <= n; i++) { if (ok[1][i]) { dp[i][1] = dis[1][i]; } } for (int i = 1; i <= n; i++) { for (int j = 1; j < i; j++) { for (int k = i+1; k <= n; k++) { if (ok[i][k] && dp[i][j] != INF) { dp[k][j+1] = min (dp[k][j+1], dp[i][j]+dis[i][k]); } } } } double ans = INF; for (int i = 1; i < n; i++) { ans = min (ans, dp[n][i]); } printf ("%.2lf\n", ans); } return 0; }