当前位置:网站首页>0-1背包问题
0-1背包问题
2022-07-27 22:24:00 【hnjzsyjyj】
【题目来源】
https://www.acwing.com/problem/content/description/2/
【题目描述】
有 N 件物品和一个容量是 V 的背包。每件物品只能使用一次。
第 i 件物品的体积是 vi,价值是 wi。
求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。
输出最大价值。
【输入格式】
第一行两个整数,N,V,用空格隔开,分别表示物品数量和背包容积。
接下来有 N 行,每行两个整数 vi,wi,用空格隔开,分别表示第 i 件物品的体积和价值。
【输出格式】
输出一个整数,表示最大价值。
【数据范围】
0<N,V≤1000
0<vi,wi≤1000
【算法代码一】
#include <bits/stdc++.h>
using namespace std;
const int maxn=1005;
int v[maxn]; //volume
int w[maxn]; //worth
int f[maxn][maxn]; //f[i][j], the maximum value of the previous i items under j volume
int main() {
int n,m;
cin>>n>>m;
for(int i=1; i<=n; i++)
cin>>v[i]>>w[i];
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++) {
//If the current backpack can't hold the i-th item, the value is equal to the previous i-1 item
if(j<v[i]) f[i][j]=f[i-1][j];
//If yes, the decision is made whether to select item i
else f[i][j]=max(f[i-1][j],f[i-1][j-v[i]]+w[i]);
}
cout<<f[n][m]<<endl;
return 0;
}
/*
in:
4 5
1 2
2 4
3 4
4 5
out:
8
*/
【算法代码二(一维数组优化)】
#include<bits/stdc++.h>
using namespace std;
const int maxn=1005;
int f[maxn];
int main() {
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++){
int v,w;
cin>>v>>w;
for(int j=m;j>=v;j--)
f[j]=max(f[j],f[j-v]+w);
}
cout<<f[m]<<endl;
return 0;
}
/*
in:
4 5
1 2
2 4
3 4
4 5
out:
8
*/
【参考文献】
https://www.acwing.com/solution/content/1374/
边栏推荐
- 网络设备硬核技术内幕 防火墙与安全网关篇 (十二) 零接触办公的奥秘 下
- Add a picture in front of the cell
- Resolved Unicode decodeerror: 'UTF-8' codec can't decode byte 0xa1 in position 0: invalid start byte
- [BuildRelease Management]Parabuild
- 2020年一季度可穿戴市场出货量达7260万部,苹果独占近三成市场份额
- 迷惑的单片机矩阵按键
- Swear, swear, swear
- 《KMP复习 + AC自动机》前传
- 深度刨析数据在内存中的存储
- Volkswagen China invested 8billion yuan and became the largest shareholder of GuoXuan high tech
猜你喜欢
随机推荐
程序员成长第三十篇:你真的懂反馈吗?
网络设备硬核技术内幕 防火墙与安全网关篇 (五) 安全双修大法 中
What is the org relationship mitigation strategy of Microsoft edge browser tracking prevention
Syntaxerror resolved: positive argument follows keyword argument
R language evaluates the relative importance of the predictive factors (variables, characteristics) of the regression model, scales the predictive variables of the regression model, and then construct
立即报名 | 云原生技术交流 Meetup 广州站已开启,8 月 6 号与你相遇!
【C语言入门】ZZULIOJ 1026-1030
Branch and loop sentence exercises
接口测试实战项目02:读懂接口测试文档,上手操练
Confused SCM matrix keys
Postman download and use tutorial
From the second floor to the third floor
In the first quarter of 2020, the wearable market shipped 72.6 million units, with apple occupying nearly 30% of the market share
MySQL limit usage and large paging problem solving
怎么清晰地理解、表达 IaaS 、 PaaS 、 SaaS ?
一文读懂CMake
推荐系统-模型(三):精排模型【LR、GBDT、Wide&Deep、DCN、DIN、DIEN、MMOE、PLE】
[BuildRelease Management]Parabuild
MySQL中的运算符
Data analysis: disassembly method (details)








![[bre] software build release automation](/img/c6/daead474a64a9a3c86dd140c097be0.jpg)
