The shortest path-dp+tsp

本文介绍了一种用于计算在特定约束条件下访问所有点的最短路径的算法。该算法适用于给定点集,其中在到达最右侧点之前,只能访问具有更大x坐标值的点;之后,则只能访问具有更小x坐标值的点。通过动态规划方法,实现了从起点到终点的最优路径计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>

#include <math.h>

using namespace std;

#define inf 0x7fffffff


struct node {

    double x,y;

};

double map[220][220],dp[220][220];


double cal(node a,node b)

{

    double x=a.x-b.x;

    double y=a.y-b.y;

    return sqrt(x*x+y*y);

}


int main()

{

    int n;

    while (~scanf("%d",&n)) {

        node coor[1001];

        int i,j;

        for (i=0; i<n; i++)

            scanf("%lf%lf",&coor[i].x,&coor[i].y);

        for (i=0; i<n; i++)

            for (j=0; j<i; j++)

                map[i][j]=map[j][i]=cal(coor[i],coor[j]);

        memset(dp, 0, sizeof(dp));

        dp[0][1]=map[0][1];

        for (i=2; i<n; i++) {

            for (j=0; j<=i-2; j++)

                dp[j][i]=dp[j][i-1]+map[i-1][i];

            dp[i-1][i]=inf;

            for (j=0; j<=i-2; j++)

                dp[i-1][i]=min(dp[i-1][i], dp[j][i-1]+map[j][i]);

            dp[i][i]=dp[i-1][i]+map[i-1][i];

        }

        printf("%.2lf\n",dp[n-1][n-1]);

    }

    return 0;

}

/*

 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

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值