uva1347 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).

首先可以把问题转化成两个人从最左端出发,沿着两条不重复、不相交的路径走。
那么用ans[i][j]表示两个人分别在i和j时,到终点的最短路。
但是有一个问题,无法知道两条路径会不会相交。
注意ans[i][j]和ans[j][i]是等价的,不妨设i≥j。于是定义ans[i][j]为所有1..i点都被走过时的最短路。
那么,下一步一定是某个人走到了i+1这个点【如果不是,比如一个人走到了i+2,那么这个人因为不能向左走所以肯定到不了i+1,那么i+1这个点肯定是由另外一个人走到,不会丢失解。】所以ans[i][j]=min(ans[i+1][j]+dis(i,i+1),ans[i+1][i]+dis(j,i+1))。前者表示i那个人走到i+1,后者表示j那个人走到j+1。
边界条件是ans[n][i]=dis(i,n) (i≠n)。
答案是ans[2][1]+dis(1,2)。

#include<cstdio>
#include<cstring>
#include<cmath>
double min(double x,double y)
{
    return x<y?x:y;
}
double map[1010][1010],ans[1010][1010];
int xx[1010],yy[1010];
int main()
{
    int i,j,k,l,m,n,p,q,x,y,z;
    while (scanf("%d",&n)==1)
    {
        for (i=1;i<=n;i++)
          scanf("%d%d",&xx[i],&yy[i]);
        for (i=1;i<=n;i++)
          for (j=1;j<=n;j++)
            map[i][j]=sqrt(double((xx[i]-xx[j])*(xx[i]-xx[j])+(yy[i]-yy[j])*(yy[i]-yy[j])));
        for (i=1;i<n;i++)
          ans[n][i]=map[i][n];
        for (i=n-1;i>=2;i--)
          for (j=i;j>=1;j--)
            ans[i][j]=min(ans[i+1][j]+map[i][i+1],ans[i+1][i]+map[j][i+1]);
        printf("%.2lf\n",ans[2][1]+map[1][2]);
    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值