动态规划小结——最优配对问题

1.说明:紫书上的最优配对问题的代码(P284)有问题,下面把完整的代码贴出来。注意把d[0]初始化为0才行,n一定要是偶数。

2.代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

#define maxn 21
const double INF = 1e10;
double d[maxn];
int n,S;
struct node
{
	int x, y, z;
}dot[1<<maxn];

double dist(int i, int j)
{
	int dx = dot[i].x - dot[j].x;
	int dy = dot[i].y - dot[j].y;
	int dz = dot[i].z - dot[j].z;
	return sqrt((double)dx*dx + dy*dy + dz*dz);
}

void solve()
{
	for (int s = 1; s < S; s++)
	{
		int i, j;
		d[s] = INF;
		for (i = n - 1; i >= 0;i--)
		if (s&(1 << i))//i是集合s中的最大值
			break;
		for (j = i - 1; j >= 0;j--)
		if (s&(1 << j))
			d[s] = min(d[s], dist(i, j) + d[s ^ (1 << i) ^ (1 << j)]);
	}
}
int main()
{
	//freopen("test.txt", "r", stdin);
	while (scanf("%d", &n) != EOF&&n)
	{
		memset(dot, 0, sizeof(dot));
		memset(d, -1, sizeof(d));
		for (int i = 0; i < n; i++)
			scanf("%d%d%d", &dot[i].x, &dot[i].y, &dot[i].z);
		S = 1 << n;
		d[0] = 0;//注意此处要初始化,书上代码有问题
		solve();
		printf("%.3lf\n", d[S - 1]);
	}
	
	return 0;
}



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