集合DP 点集匹配问题

刘汝佳大白书p61页


#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>

using namespace std;

#define INF 0x3f3f3f3f
#define N 21

struct point
{
    double x, y, z;
} P[N];
double x[N], y[N];
double d[1 << N];

double dist(point a, point b)
{
    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z));
}


int main()
{
    freopen("BB.txt", "r", stdin);
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
        scanf("%lf%lf%lf", &P[i].x, &P[i].y, &P[i].z);
    }
    for(int i = 0; i < (1 << n); i++)
       d[i] = INF;
    d[0] = 0;

    for(int s = 3; s < (1 << n) ; s++)
    {
        int i, j;
        for(i = 0; i < n; i++)
        if(s & (1 << i))
        break;
        for(j = i + 1; j < n; j++)
        if(s & (1 << j))
        d[s] = min(d[s], d[s ^ (1<<i) ^ (1<<j)] + dist(P[i], P[j]));
    }
    printf("%.3lf\n", d[(1<<n)-1]);
    return 0;
}

/*
20
1 2 3
1 1 1
5 6 2
4 7 8
2 3 1
1 4 7
2 5 8
3 6 9
1 2 5
2 3 6
4 5 2
7 8 5
4 5 1
-1 2 3
-1 -9 -7
0 0 0
100 0 0
9 5 1
7 5 3
5 5 5
*/


你可能感兴趣的:(dp,ACM)