您的位置:首页 > 其它

HDU 2224 The shortest path

2014-09-25 14:05 459 查看


The shortest path

Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 772 Accepted Submission(s): 400



Problem Description

There are n points on the plane, Pi(xi, yi)(1 <= i <= n), and xi < xj (i<j). You begin at P1 and visit all points then back to P1. But there is a constraint:

Before you reach the rightmost point Pn, you can only visit the points those have the bigger x-coordinate value. For example, you are at Pi now, then you can only visit Pj(j > i). When you reach Pn, the rule is changed, from now on you can only visit the points
those have the smaller x-coordinate value than the point you are in now, for example, you are at Pi now, then you can only visit Pj(j < i). And in the end you back to P1 and the tour is over.

You should visit all points in this tour and you can visit every point only once.



Input

The input consists of multiple test cases. Each case begins with a line containing a positive integer n(2 <= n <= 200), means the number of points. Then following n lines each containing two positive integers Pi(xi, yi), indicating the coordinate of the i-th
point in the plane.



Output

For each test case, output one line containing the shortest path to visit all the points with the rule mentioned above.The answer should accurate up to 2 decimal places.



Sample Input

3
1 1
2 3
3 1




Sample Output

6.47

Hint: The way 1 - 3 - 2 - 1 makes the shortest path.




Author

8600

解题思路:双调TSP问题,求一个人从左到右按X轴坐标严格递增的顺序走到最右然后从右到左按X轴严格递减的顺序再走回原点的最短路径,令dp[i][j]表示从i按要求走到原点再从原点走到j 的最短距离,dp[i+1][i]=min(dp[i][j])+dis[i+1][j];

dp[i+1][j]=min(dp[i][j])+dis[i][i+1];

#include <cstdio>
#include <cstring>
#include <cmath>
const int MAXN = 205;
const double INF = 1e100;

double dp[MAXN][MAXN];
int x[MAXN], y[MAXN];

inline double min(double x, double y)
{
    return x < y ? x : y;
}

inline double getDistance(int x1, int y1, int x2, int y2)
{
    return sqrt(1.0 * (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

inline double getDistance(int i, int j)
{
    return getDistance(x[i], y[i], x[j], y[j]);
}

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        for(int i=0;i<n;++i)
        {
            scanf("%d%d", &x[i], &y[i]);
            for(int j=0;j<n;++j)
            {
                dp[i][j] = INF;
            }
        }
        dp[1][0] = getDistance(1, 0);
        for(int i=0;i<n-1;++i)
        {
            for(int j=0;j<i;++j)
            {
                dp[i+1][i] = min(dp[i+1][i], dp[i][j] + getDistance(j, i+1));
                dp[i+1][j] = min(dp[i+1][j], dp[i][j] + getDistance(i, i+1));
            }
        }
        double ans = INF;
        for(int j=0;j<n-1;++j)
        {
            ans = min(ans, dp[n-1][j] + getDistance(j, n-1));
        }
        printf("%.2lf\n", ans);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: