[UVA][dp] 1347 - Tour
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.
Input
The program input is from a text file. Each data set in the file 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.
Output
For each set of data, your program should print the result to the standard output from the beginning of a line. The tour length, a floating-point number with two fractional digits, represents the result.
Note: An input/output sample is in the table below. Here there are two data sets. The first one contains 3 points specified by their x
and y
coordinates. The second point, for example, has the x
coordinate 2, and the y
coordinate 3. The result for each data set is the tour length, (6.47 for the first data set in the given example).
Sample Input
3 1 1 2 3 3 1 4 1 1 2 3 3 1 4 2
Sample Output
6.47 7.89
題目描述:
從最左邊的點出發,第一趟必須全部往右邊走,到達最右邊的點,第二趟全部往左走,回到原點。
兩趟要走過所有點。
題目解法:
雖然題目要求全往右之後,全往左。但事實上可當作兩條路徑同時向右經過左所有點。
dp[i][j] 表示第一條路徑的最後一點 i, 第二條路徑的最後一點 j, 而下一個必須被加入的點一定是
max(i, j)+1,然後考慮這一點要接在第一條路徑之後,還是第二條路徑之後。
這題明明比 [UVA][dp] 1096 - The Islands 簡單很多,但在 Competitive Programming Exercises 第三版中被判定是 Level 8 ? 還是 uhunt 上面寫錯?還是我假解了?
#include <stdio.h>
#include <math.h>
#include <algorithm>
using namespace std;
double dp[105][105];
int main() {
int n;
int i, j, k;
double x[105], y[105];
while(scanf("%d", &n) == 1) {
if(n == 0) break;
for(i = 0; i < n; i++)
scanf("%lf %lf", &x[i], &y[i]);
double ret = 1e+60;
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++)
dp[i][j] = 1e+60;
}
dp[0][0] = 0;
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
k = max(i, j)+1;
dp[i][k] = min(dp[i][k], dp[i][j] + hypot(x[k]-x[j], y[k]-y[j]));
dp[k][j] = min(dp[k][j], dp[i][j] + hypot(x[k]-x[i], y[k]-y[i]));
}
}
for(i = 0; i < n; i++) {
ret = min(ret, dp[i][n-1] + hypot(x[n-1]-x[i], y[n-1]-y[i]));
ret = min(ret, dp[n-1][i] + hypot(x[n-1]-x[i], y[n-1]-y[i]));
}
printf("%.2lf\n", ret);
}
return 0;
}