Luo Gu P1523 simplified version of the traveling salesman (DP)

Title:
p1523 simplified version of the traveling salesman
parsing
disposed \ (f [i] [j ] \) represents a person walked i, j one of the shortest distance walked ( \ (I <j \) )
of \ (j + 1 \) positions, two people are likely to go, the two cases

  • \ (f [i] [j + 1] = min \ {f [i] [j + 1], f [i] [j] + dis [j] [j + 1] \} \) position j, people come to j + 1 position
  • \ (f [j] [j + 1] = min \ {f [j] [j + 1], f [i] [j] + dis [i] [j + 1] \} \) position i, people come to j + 1 position

Code:

#include <bits/stdc++.h>
using namespace std;
const int N = 1010;

int n, m;
double f[N][N], dis[N][N];

struct node {
    double x, y;
    bool operator <(const node &oth) const {
        return x < oth.x;
    }
} e[N];

double calc(node a, node b) {
    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}

int main() {
    ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 1; i <= n; ++i)
        cin >> e[i].x >> e[i].y;
    sort(e + 1, e + 1 + n);
    for (int i = 1; i <= n; ++i) 
        for (int j = i + 1; j <= n; ++j) 
            dis[i][j] = calc(e[i], e[j]), f[i][j] = LLONG_MAX;
    f[1][2] = dis[1][2];
    for (int i = 1; i <= n; ++i)
        for (int j = i + 1; j <= n; ++j) {
            f[i][j + 1] = min(f[i][j + 1], f[i][j] + dis[j][j + 1]);
            f[j][j + 1] = min(f[j][j + 1], f[i][j] + dis[i][j + 1]);
        }
    double ans = LLONG_MAX;
    for (int i = 1; i < n; ++i) ans = min(ans, f[i][n] + dis[i][n]);
    printf("%.2lf", ans);
}

Guess you like

Origin www.cnblogs.com/lykkk/p/11692713.html