POJ 2677 Tour

题意:双调欧几里得旅行商问题。算法导论15-1题,从最左边的点严格从左走到右再从右走到左回到起点,所有点都要走且只走一次,求最短路径。

解法:定义dp[i][j]表示从i走到j的双调路径,分为两种情况:

  1. 当j < i - 1时,dp[i][j] = dp[i - 1][j] + dis[i - 1][i]
  2. 当j = i - 1时,dp[i][j] = min{dp[j][k] + dis[j][k]}

最初的情况是dp[2][1] = dis[2][1]。

代码:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define LL long long
using namespace std;
struct node
{
    int x, y;
    bool operator < (const node& tmp) const
    {
        if(x == tmp.x)
            return y < tmp.y;
        else
            return x < tmp.x;
    }
} point[2005];
double dp[2005][2005];
double dis[2005][2005];
int main()
{
    //freopen("in.txt", "r", stdin);
    int n;
    while(~scanf("%d", &n))
    {
        memset(dp, 0, sizeof(dp));
        for(int i = 0; i < n; i++)
            scanf("%d%d", &point[i].x, &point[i].y);
        sort(point, point + n);
        for(int i = 0; i < n; i++)
            for(int j = i + 1; j < n; j++)
            {
                double d = sqrt((point[i].x - point[j].x) * (point[i].x - point[j].x) + (point[i].y - point[j].y) * (point[i].y - point[j].y));
                dis[i][j] = dis[j][i] = d;
            }
        dp[1][0] = dis[1][0];
        for(int i = 2; i < n; i++)
        {
            for(int j = 0; j < i - 1; j++)
                dp[i][j] = dp[i - 1][j] + dis[i][i - 1];
            dp[i][i - 1] = 1e10;
            for(int j = 0; j < i - 1; j++)
                dp[i][i - 1] = min(dp[i][i - 1], dp[i - 1][j] + dis[j][i]);
        }
        if(n == 2)
            dp[1][1] = dis[1][0];
        else
            dp[n - 1][n - 1] = dp[n - 1][n - 2] + dis[n - 2][n - 1];
        printf("%.2lf\n", dp[n - 1][n - 1]);
    }
    return 0;
}

你可能感兴趣的:(动态规划)