当前位置:网站首页>输出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
边栏推荐
猜你喜欢
随机推荐
D - Draw Your Cards(模拟)
有谁知道pg12.5版本的数据库驱动在哪里能找到么?
Pytorch - Distributed Model Training
十九届浙大城院程序设计竞赛 F.Sum of Numerators(数学/找规律)
【二叉树】路径总和II
考研大事件!这6件事考研人必须知道!
微信UI在线聊天源码 聊天系统PHP采用 PHP 编写的聊天软件,简直就是一个完整的迷你版微信
大佬们,datax同步数据,同步过程中要新增一个uuid,请问column 怎么写pgsql,uu
使用ffmpeg来查看视频的信息,fps,和width,height
openEuler 社区12位开发者荣获年度开源贡献之星
win10+Qt5.15.2实现低功耗蓝牙控制
lua脚本关键
gpio analog serial communication
A Beginner's Guide to Performance Testing
What is a closure?
MySQL中的行锁
性能测试入门指南
微服务系统架构的演变
响应式2022英文企业官网源码,感觉挺有创意的
HTB-Shocker









