当前位置:网站首页>输出0-1背包问题的具体方案 ← 利用二维数组
输出0-1背包问题的具体方案 ← 利用二维数组
2022-08-01 14:34: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 vol[maxn]; //volume
int val[maxn]; //value
int c[maxn][maxn]; //c[i][j], the maximum value of the previous i items under j volume
int f[maxn];
int main() {
int n,m;
cin>>n>>m;
for(int i=1; i<=n; i++)
cin>>vol[i]>>val[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<vol[i]) c[i][j]=c[i-1][j];
//If yes, the decision is made whether to select item i
else c[i][j]=max(c[i-1][j],c[i-1][j-vol[i]]+val[i]);
}
cout<<c[n][m]<<endl;
for(int i=n,j=m;i>0;i--){
if(c[i][j]>c[i-1][j]){
f[i]=1;
j-=vol[i];
}
else f[i]=0;
}
cout<<"The items put into the backpack are: ";
for(int i=1;i<=n;i++){
if(f[i]==1){
cout<<i<<" ";
}
}
return 0;
}
/*
in:
5 4
1 20
4 30
1 15
3 20
1 10
out:
45
The items put into the backpack are: 1 3 5
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/125987923
边栏推荐
猜你喜欢

全球都热炸了,谷歌服务器已经崩掉了

HTB-Mirai

响应式2022英文企业官网源码,感觉挺有创意的

十九届浙大城院程序设计竞赛 F.Sum of Numerators(数学/找规律)
![[LiteratureReview]Optimal and Robust Category-level Perception: Object Pose and Shape Estimation f](/img/bc/f3cea50c157f151a1ca5e540e7f77b.png)
[LiteratureReview]Optimal and Robust Category-level Perception: Object Pose and Shape Estimation f

SQL每日一练(牛客新题库)——第3天: 条件查询

什么是混合元编程

The soul asks: How does MySQL solve phantom reads?

直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践

openEuler 社区完成首批顾问专家聘用,共同为社区的发展贡献力量
随机推荐
tkinter-TinUI-xml实战(6)问卷
细读《阿里测试之道》
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践
免费使用高性能的GPU和TPU—谷歌Colab使用教程
尾牙宴是什么
Could not write header for output file #0 (incorrect codec parameters ?): ……
Timezone setting in MySQL
The little thing about Request reuse.The research is understood, and I will report it to you.
Bloom filter bloom
【码蹄集新手村600题】判断一个数字是否为完全平方数
AtCoder Beginner Contest 261 D - Flipping and Bonus
Longkou united chemical registration: through 550 million revenue xiu-mei li control 92.5% stake
考研大事件!这6件事考研人必须知道!
我寻找的方向
微信UI在线聊天源码 聊天系统PHP采用 PHP 编写的聊天软件,简直就是一个完整的迷你版微信
牛客刷SQL--6
math.pow()函数用法[通俗易懂]
大神们,ODPS用的是MySQL吗?
产品力无提升的雷克萨斯新款ES ,为何敢于涨价?
游戏元宇宙发展趋势展望分析