0-1背包问题
来源:互联网 发布:模拟基金交易软件 编辑:程序博客网 时间:2024/06/18 06:03
问题描述:有n种物品,每种只有一个。第i种物品的体积为Vi,重量为Wi。选一些 物品装到一个容量为C的背包,使得背包内物品在总体积不超过C的前提下重量尽量大。 1≤n≤100,1≤Vi≤C≤10000,1≤Wi≤10 6。
解题方法①:d(i,j)=max(d(i+1,j),d(i+1,j-v[i])+w[i])
d(i,j)的意思是把(i,i+1,i+2,……..n)个物品装到容量为j的背包中的总重量,此时当第i个物品不能放进背包时他的最优解就是由d(i+1,j)决定 当i个物品能够放进背包时他的最优解就是d(i+1,j-v[i])加上i的价值w[i]
同理也可以得到对称状态②: f(i,j)=max(f(i-1,j),f(i-1,j-v[i])+w[i])
状态②代码
#include <iostream>#include <queue>#include <functional>using namespace std;const int maxn = 100;int vis[maxn], d[maxn],f[maxn][maxn];int v[maxn], w[maxn];int n, c;int main(){ int v, w; cin >> n>>c; for (int i = 1; i <= n; i++) { cin >> v >> w; for (int j = 0; j <= c; j++) { f[i][j] = (i == 1 ? 0 : f[i - 1][j]); if (j >= v) f[i][j] = max(f[i][j], f[i - 1][j-v] + w); } } cout << f[n][c] << endl; system("pause");}
状态①代码
#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <algorithm>#include <set>using namespace std;const int maxn = 100;int v[maxn], w[maxn];int d[maxn][maxn];int main(){ int n, c; cin >> n >> c; for (int i = 1; i <= n; i++) cin >> v[i] >> w[i]; for (int i = n; i >= 1; i--) { for (int j = 0; j <= c; j++) { d[i][j] = (i == n ? 0 : d[i+1][j]); if (j >= v[i]) { d[i][j] = max(d[i][j], d[i + 1][j - v[i]] + w[i]); } } } cout << d[1][c] << endl; system("pause");}
也可以将数组变成变成一维的,滚动数组可以减少内存开销,但是打印方案比较困难。
测试数据n=5 ,c=5
v w={(1,5),(2,3),(3,10),(4,9),(5,1)}
#include <iostream>#include <queue>#include <functional>#include <algorithm>#include <cstring>using namespace std;const int maxn = 100;int f[maxn];int n, c;int main(){ int v, w; memset(f,0,sizeof(f)); cin >> n>>c; for (int i = 1; i <= n; i++) { cin >> v >> w; for(int j=c;j>=0;j--) { if(j>=v) f[j]=max(f[j],f[j-v]+w); } } cout << f[c] << endl; system("pause");}
阅读全文
0 0
- 背包问题(0-1背包、完全背包、多重背包)详解
- 背包问题和0-1背包问题
- 背包问题和0-1背包问题
- 背包问题系列--"0-1背包问题"
- 背包笔记-含0/1背包问题、完全背包问题、多重背包问题、二维背包问题、分组背包问题
- 【背包问题】背包问题之0-1背包、完全背包、多重背包
- 0-1背包问题
- 0/1背包问题
- 0,1背包问题
- 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- // 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- 0-1背包问题
- 0-1背包问题
- 0/1背包问题
- ABP理论学习之事件总线和领域事件
- 深度学习优化方法总结
- C++14 智能指针unique_ptr、shared_ptr、weak_ptr
- Codeforces791 C. Bear and Different Names
- v-for 指令
- 0-1背包问题
- ARouter源码解析01-编译生成文件
- 云平台建设学习6
- 驱动程序调试常用方法
- Python学习三——列表
- 面试题 44: 扑克牌的顺子
- HDU--2031--十进制转换到任意进制
- 【分析】深入探究 C++ 引用
- 解决maven 项目启动 javax.validation.ValidationException: HV000183: Unable to initialize 'javax.el.Expressi