我是靠谱客的博主 痴情白昼,这篇文章主要介绍C++回溯法求0-1背包问题,现在分享给大家,希望可以做个参考。

主要思想:先将数组w和数组p按照单价进行排序,利用结构体的index保存其下标。

bound函数是求当前最大可能价值。

backtrack函数是利用回溯法,如果增加当前物品,则想x[i]=1,否则为0。当i>n时,递归调用结束,并且更新数组bestx和bestp。

复制代码
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
70
71
72
73
74
75
76
77
78
#include <iostream> #include <algorithm> #define N 4 using namespace std; int c = 7, w[N+1] = {0,3,5,2,1}, p[N+1]={0,9,10,7,4}, cw = 0, cp = 0, bestp = 0, bestx[N+1] = {0}, x[N+1] = {0}; struct node { double v; int index; }no[N+1]; bool cmp(struct node n1, struct node n2) { return n1.v > n2.v; } void sort_value() { for(int i = 1; i <= N; i++) { no[i].v = 1.0*p[i]/w[i]; no[i].index = i; } sort(no+1,no+N,cmp); } double bound(int i) { double cleft = c - cw; double bound = cp; while(i <= N && w[no[i].index] <= cleft) { cleft -= w[no[i].index]; bound += p[no[i].index]; i++; } if(i <= N) bound += p[no[i].index] / w[no[i].index] * cleft; return bound; } void backtrack(int i) { if(i > N) { if(cp > bestp) { for(int j = 1; j <= N; j++) bestx[no[j].index] = x[no[j].index]; bestp = cp; } return; } if(cw + w[no[i].index] <= c) { x[no[i].index] = 1, cw += w[no[i].index], cp += p[no[i].index]; backtrack(i+1); cw -= w[no[i].index], cp -= p[no[i].index]; } if(bound(i+1) > bestp) { x[no[i].index] = 0; backtrack(i+1); } } int main() { sort_value(); backtrack(1); for(int i = 1; i <= N; i++) cout << bestx[i] << ' '; cout << endl; cout << bestp << endl; return 0; }

最后

以上就是痴情白昼最近收集整理的关于C++回溯法求0-1背包问题的全部内容,更多相关C++回溯法求0-1背包问题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(79)

评论列表共有 0 条评论

立即
投稿
返回
顶部