当前位置:网站首页>2. 01背包问题
2. 01背包问题
2022-06-28 12:55:00 【HHppGo】
题目:
有 N 件物品和一个容量是 V 的背包。每件物品只能使用一次。
第 i 件物品的体积是 vi,价值是 wi。
求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。
输出最大价值。
输入格式:
第一行两个整数,N,V,用空格隔开,分别表示物品数量和背包容积。
接下来有 N 行,每行两个整数 vi,wi,用空格隔开,分别表示第 i 件物品的体积和价值。
输出格式:
输出一个整数,表示最大价值。
数据范围:

输入样例:
4 5
1 2
2 4
3 4
4 5
输出样例:
8
思路:

解法一代码:
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1100;
int n,m;
int f[N][N],v[N],w[N];
int main()
{
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= 0;j<=m;j++)
{
f[i][j] = f[i-1][j];
if(j >= v[i] ) f[i][j] = max(f[i][j],f[i-1][j-v[i]] + w[i]);
}
cout<<f[n][m]<<endl;
return 0;
}
解法二代码:(优化后的一维做法)
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1100;
int n,m;
int f[N],v[N],w[N];
int main()
{
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=m;j>=v[i];j--)
{
f[j] = max(f[j],f[j-v[i]] + w[i]);
}
cout<<f[m]<<endl;
return 0;
}
边栏推荐
- Fastposter v2.8.4 release e-commerce poster generator
- 一文搞懂leveldb写操作
- ASP.NET CORE Study03
- 杰理之wif 干扰蓝牙【篇】
- 高考失利進哈工大,畢業卻留校要當“探索者”,丁效:科研就是厚積薄發
- ASP.NET CORE Study07
- 微服务稳定性保障
- ASP.NET CORE Study01
- Après avoir échoué à l'examen d'entrée à l'Université de technologie de Harbin, vous devez rester à l'Université en tant que « chercheur » après avoir obtenu votre diplôme.
- FineReport安装教程
猜你喜欢

centos6.5 php+mysql mysql库找不到

group_ Concat learning and configuration

ASP. NET CORE Study03

Unity Editor Extension Foundation, GUI

在线JSON转PlainText工具

结构光之相移法+多频外差的数学原理推导

关于IP定位查询接口的测评Ⅰ

腾讯汤道生:面向数实融合新世界,开发者是最重要的“建筑师”

Copying open source for basic software is not advisable. Self reliance is the right way

基于SSM实现水果蔬菜商城管理系统
随机推荐
性能测试-01-简介
JS duration and asynchronous function promise
Centos6.5 php+mysql MySQL library not found
杰理之SPI1外挂FLASH录音修改【篇】
从 jsonpath 和 xpath 到 SPL
Validateur async. Vérificateur de données JS
几百行代码实现一个 JSON 解析器
Digital twin energy system, creating a "perspective" in the low-carbon era
.NET混合开发解决方案24 WebView2对比CefSharp的超强优势
go template with...end遍历用法
易观分析《2022年中国银行业隐私计算平台供应商实力矩阵分析》研究报告正式启动
##测试bug常用“Redmine”
Which securities company is the best and safest? How to open an account is the safest
Namespace and scope
K3s one click installation script
Tencent has confirmed that QQ has stolen numbers on a large scale, iphone14 has no chance of type-C, and 5g, the fourth largest operator, has officially released numbers. Today, more big news is here
Unity releases webgl and wakes up keyboard input on the mobile terminal inputfield
【云原生】自助报表和BI能做这么多事?
Vs2012 VC creates a new blank window application
group_ Concat learning and configuration