最优点配对问题

问题:

给出平面上n(n是偶数)个点,两两之间距离为欧几里得距离,求一种两两配对对的方式,使他们连的边总长最小

代码:

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

#define rep(i,x,y) for (int i=x;i<=y;i++)
#define read(x) scanf("%d",&x)

using namespace std;

const int maxn=21;
const double inf=1000000;

double x[maxn],y[maxn],d[1<<maxn];
int n;

double dist(int a,int b)
{
  return sqrt((x[a]-x[b])*(x[a]-x[b])+(y[a]-y[b])*(y[a]-y[b]));
}

double solve()
{
 d[0]=0;
 rep(s,1,(1<<n)-1) 
 {
   int i,j;
   d[s]=inf;
   for (i=0;i<n;i++) //find smallest num
    if (s & (1<<i)) break;
   for (j=i+1;j<n;j++)
    if (s & (1<<j)) d[s]=min(d[s],dist(i,j)+d[s^(1<<i)^(1<<j)]); //DP Function
 }
 return d[(1<<n)-1];
}

int main()
{
 read(n);
 rep(i,0,n-1)
   scanf("%lf%lf",&x[i],&y[i]);
 
 printf("%.3lf\n",solve());
 system("pause");
 return 0;
}

posted @ 2016-01-24 09:51  Krew  阅读(218)  评论(0)    收藏  举报