1.说明:紫书上的最优配对问题的代码(P284)有问题,下面把完整的代码贴出来。注意把d[0]初始化为0才行,n一定要是偶数。
2.代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69#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("%.3lfn", d[S - 1]); } return 0; }
最后
以上就是时尚灰狼最近收集整理的关于动态规划小结——最优配对问题的全部内容,更多相关动态规划小结——最优配对问题内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复