UVA-1347

UVA-1347

题目大意:给出几个坐标,求从左边到右边再回来遍历所有点的最短路径

解题思路:转换思想为俩个人从不同路走过去的总路程最短的路
dp[i][j]表示第一个人到i点第二人到j点,j到i之间的点全部走过了的最短路
dp[i][j] = dp[i-1][j] + dis(i,i-1);
dp[i][i-1] = min (dp[i][i-1], dp[i-1][j] + dis(i, j));

#include 
#include 
#include 
#include 
using namespace std;

struct point {
    double x;
    double y;
};
int n;
double re;
double dp[1000][1000];
int p, q;
point po[1000];
double dis(int a, int b) {
    double c;
    c = sqrt((po[a].x - po[b].x) * (po[a].x - po[b].x) + (po[a].y - po[b].y) * (po[a].y - po[b].y));
    return c;
}

int main() {
    while(scanf("%d", &n) != EOF) {
        for(int i = 0; i < n; i++) {
            cin >> po[i].x;
            cin >> po[i].y;
        }
        memset(dp, 0, sizeof(dp));
        dp[1][0] = dis(1, 0);
        for(int i = 2; i < n; i++) {
            for(int j = 0; j < i-1; j++) {
                if(dp[i][i-1] == 0 || dp[i][i-1] > dp[i-1][j] + dis(j, i))
                    dp[i][i-1] = dp[i-1][j] + dis(j, i);
                dp[i][j] = dp[i-1][j] + dis(i-1, i);
            }
        }
        re = 0;
        for(int i = 0; i < n-1; i++) {
            if(re == 0 || re > dp[n-1][i] + dis(i, n-1))
                re = dp[n-1][i] + dis(i, n-1);
        }
        printf("%.2lf\n", re);
    }
    return 0;
}

你可能感兴趣的:(动态规划,小白,刷题)