最优配对问题:空间里有n个点P0,P1,…,Pn-1,你的任务是把它们配成n/2对(n是偶数),使得每个点恰好在一个点对中。所有点对中两点的距离之和应尽量小。
1.设d(i, s)表示前i个点中,位于集合s中的元素两两配对的最小距离和
则状态转移方程 d(i,S)=min{|PiPj|+d(i-1,S-{i}-{j}
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include <iostream>
using namespace std;
#define maxn 21
#define INF 1e10
struct Node{
int x, y, z;
}node[maxn];
int n;
double d[maxn][1<<maxn];
double dis(Node &a, Node &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));
}
void dp()
{
for(int i = 0; i < n; i++)
{
for(int s = 0; s < (1 << i+1); s++)
{
if(s == 0)d[i][s] = 0;
else d[i][s] = INF;
if(s & (1 << i))
for(int h = 0; h < i; h++){
if(s & (1 << h))
d[i][s] = min(d[i][s], dis(node[i], node[h]) + d[i-1][s^(1<<h)^(1<<i)]);
}
else if(i)
d[i][s] = d[i-1][s];
}
}
}
int main()
{
// freopen("in.txt", "r", stdin);
cin >> n;
for(int i = 0; i < n; i++)
cin >> node[i].x >> node[i].y >> node[i].z;
dp();
cout << d[n-1][(1<<n)-1] << endl;
}
2.用d(s)表示集合s中的元素两两配对的最小距离和
状态转移方程:d(S)=min{|PiPj|+d(S-{i}-{j}} i = max(s).
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include <iostream>
using namespace std;
#define maxn 21
#define INF 1e10
struct Node{
int x, y, z;
}node[maxn];
int n;
double d[1<<maxn+1];
double dis(Node &a, Node &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));
}
void dp()
{
d[0] = 0;
for(int s = 1; s < (1 << n); s++)
{
int j;
d[s] = INF;
for(j = n-1; j >= 0; j--)
if(s & (1<<j))
break;
for(int i = 0; i < j; i++)
{
if(s & (1<<i))
d[s] = min(d[s], dis(node[i], node[j]) + d[s^(1<<i)^(1<<j)]);
}
}
}
int main()
{
//freopen("in.txt", "r", stdin);
cin >> n;
for(int i = 0; i < n; i++)
cin >> node[i].x >> node[i].y >> node[i].z;
dp();
cout << d[(1<<n) - 1] << endl;
}
3.用递归实现第二种方法,则可不用计算s中的点个数为奇数的情况.
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include <iostream>
using namespace std;
#define maxn 21
#define INF 1e10
struct Node{
int x, y, z;
}node[maxn];
int n;
double d[1<<maxn+1];
double dis(Node &a, Node &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));
}
double dp(int s)
{
if(d[s] != -1)
return d[s];
int i;
d[s] = INF;
for(i = n-1; i >= 0; i--)
if(s & (1<<i))
break;
for(int j = 0; j < i; j++)
if(s & (1<<j))
d[s] = min(d[s], dis(node[i], node[j]) + dp(s ^ (1<<i) ^ (1<<j)));
return d[s];
}
int main()
{
// freopen("in.txt", "r", stdin);
cin >> n;
for(int i = 0; i < n; i++)
cin >> node[i].x >> node[i].y >> node[i].z;
d[0] = 0;
for(int i = 1; i < (1<<n); i++)
d[i] = -1;
dp((1<<n) - 1);
cout << d[(1<<n) - 1] << endl;
}
Input:
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
Output:
119.076