当前位置:网站首页>输出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
边栏推荐
猜你喜欢
随机推荐
docker部署mysql并修改其占用内存大小
珠海首个水环境安全监测系统上线
SQL查询语句之查询数据
牛客刷SQL--6
MBI5020 LED Driver
ABC260 E - At Least One(双指针)
datetime64[ns] converted to datetime
xmind2testcase:高效的测试用例导出工具
E - Red and Blue Graph (Combinatorics)
php gui 框架 demo
你真的会测试用户登录吗?
A Beginner's Guide to Performance Testing
沃文特生物IPO过会:年营收4.8亿 养老基金是股东
win10+Qt5.15.2实现低功耗蓝牙控制
HTB-Shocker
轮询和长轮询的区别
Typora报错:This beta version of Typora is expired
The little thing about Request reuse.The research is understood, and I will report it to you.
经纬信息IPO过会:年营收3.5亿 叶肖华控制46.3%股权
HTB-Mirai