标签:mon action Plan style 动态 script length scanf ace
John Doe, a skilled pilot, enjoys traveling. While on vacation, he rents a small plane and starts visiting beautiful places. To save money, John must determine the shortest closed tour that connects his destinations. Each destination is represented by a point in the plane pi =< xi,yi >. John uses the following strategy: he starts from the leftmost point, then he goes strictly left to right to the rightmost point, and then he goes strictly right back to the starting point. It is known that the points have distinct x-coordinates. Write a program that, given a set of n points in the plane, computes the shortest closed tour that connects the points according to John’s strategy.
The program input is from a text ?le. Each data set in the ?le stands for a particular set of points. For each set of points the data set contains the number of points, and the point coordinates in ascending order of the x coordinate. White spaces can occur freely in input. The input data are correct.
6.47
7.89
题解:这个题代码虽然比较短,但是状态的定义真的是很秀,不知道下一次再遇到类似的题自己能不能想到这样定义状态。首先,从左到右再从右到左一般都是化为两个从左到右,dp[i][j]为第一个人到i,第二个人到j,并且标号<=min(i,j)都已经走过,很显然dp[i][j] == dp[j][i],因此不妨规定i > j,因此dp[i][j]只能从dp[i+1][i],或dp[i+1][j]转移过来,记忆化搜索就好。
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 const int maxn = 1000 + 10; 6 7 int n; 8 9 struct Point { 10 int x, y; 11 }point[maxn]; 12 13 double dist[maxn][maxn]; 14 double dp[maxn][maxn]; 15 16 double DP(int i, int j) { 17 double& ans = dp[i][j]; 18 if (ans > 0) return ans; 19 20 ans = 0.0; 21 if (i == n - 1) { 22 ans = dist[n - 1][n] + dist[j][n]; 23 } 24 else { 25 ans = min(dist[i][i + 1] + DP(i + 1, j), dist[j][i + 1] + DP(i + 1, i)); 26 } 27 return ans; 28 } 29 30 int main() 31 { 32 //freopen("input.txt", "r", stdin); 33 while (~scanf("%d", &n) && n) { 34 for (int i = 1; i <= n; i++) { 35 scanf("%d%d", &point[i].x, &point[i].y); 36 } 37 38 for (int i = 1; i <= n; i++) { 39 for (int j = 1; j <= n; j++) { 40 dp[i][j] = -1.0; 41 dist[j][i] = dist[i][j] = sqrt(1.0*(point[i].x - point[j].x)*(point[i].x - point[j].x) + 1.0*(point[i].y - point[j].y)*(point[i].y - point[j].y)); 42 } 43 } 44 45 printf("%.2f\n", DP(1, 1)); 46 } 47 return 0; 48 }
标签:mon action Plan style 动态 script length scanf ace
原文地址:https://www.cnblogs.com/npugen/p/9727266.html