UVA - 1347 Tour

本文介绍了一种解决旅行商问题(TSP)的方法,利用动态规划算法来计算两个旅行者从同一地点出发,不重复经过任意节点的情况下到达终点的最短路径。文章详细描述了状态表示及状态转移方程。

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时,两个人离终点剩下的最短距离

通过观察发现几个规律

1. 两个人是可以互换的,所以dp[i][j]=dp[j][i]

2. 如何判断第二个人不会重复走第一个人的路, 可以根据1我们可以假定第一个人先走过的路第二个人不会走,这样每当第二个人走的时候,下一步就是 dp[i][i+1] = dp[i+1][i]

3. 根据2可以得到转移方程 dp[i][j] = min(dis(i,i+1) + dp[i+1][j],  dis(j, i+1) + dp[i+1][1])

 

#include <iostream>
#include <cmath>
#include <string.h>
#define NUM 1000
using namespace std;
int N;
double dp[NUM][NUM];
struct {
    int x, y;
} d[NUM];

double getDp(int i, int j);

double dist(int i, int j);

int main() {
    while (cin >> N && N) {
        memset(dp, 0, sizeof(dp));
        for (int i = 1; i <= N; ++i) {
            cin >> d[i].x >> d[i].y;
        }
        printf("%.2f\n", getDp(1, 1));
    }
}

double getDp(int i, int j) {
    if (dp[i][j] != 0)
        return dp[i][j];
    if (i == N)
        return dp[i][j] = dist(i, j);
    return dp[i][j] = min(dist(i, i + 1) + getDp(i + 1, j), dist(j, i + 1) + getDp(i + 1, i));
}

double dist(int i, int j) {
    return sqrt(pow(d[i].x - d[j].x, 2) + pow(d[i].y - d[j].y, 2));
}

 

转载于:https://www.cnblogs.com/wangsong/p/8012727.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值