当前位置: 首页 > news >正文

Book Shop(Dynamic Programming)

题目描述

You are in a book shop which sells n different books. You know the price and number of pages of each book.
You have decided that the total price of your purchases will be at most x. What is the maximum number of pages you can buy? You can buy each book at most once.

输入

The first input line contains two integers n and x: the number of books and the maximum total price.
The next line contains n integers h1,h2,...,hn: the price of each book.
The last line contains n integers s1,s2,...,sn: the number of pages of each book.
Constraints
1 ≤ n ≤ 1000
1 ≤ x ≤ 10^5
1 ≤ hi, si ≤ 1000

输出

Print one integer: the maximum number of pages.

样例输入
4 10
4 8 5 3
5 12 8 1
样例输出
13
提示

You can buy books 1 and 3. Their price is 4+5=9 and the number of pages is 5+8=13.

思路分析

动态规划。

既然每种书至多买一本,就对所有书仅仅遍历一遍。

嵌套循环,外层是所有书籍,i从0到n。内层是所花的钱,从x到1逆序遍历。

如果正序遍历,会出现一本书买多次的情况。以本题为例,当i=2,j=5时,dp[5]=8,j=10时,dp[10]=16,就会出现错误。

代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n,x,ans;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>n>>x;vector<ll>h(n,0),s(n,0);for(ll i=0;i<n;i++){cin>>h[i];}for(ll i=0;i<n;i++){cin>>s[i];}vector<ll>dp(x+5,0);for(ll i=0;i<n;i++){for(ll j=x;j>=h[i];j--){dp[j]=max(dp[j-h[i]]+s[i],dp[j]);}}cout<<dp[x];return 0;
}
http://www.dtcms.com/a/316222.html

相关文章:

  • Direct12第六章
  • 【LeetCode 热题 100】347. 前 K 个高频元素——(解法一)排序截取
  • 防火墙的区域划分和流量控制
  • Qwen3技术之模型预训练
  • Redis Stream:高性能消息队列核心原理揭秘
  • 数据结构04 栈和队列
  • tensorRT配合triton部署模型
  • C语言的结构体与联合体
  • LOOP Finance:一场 Web3 共和国中的金融制度实验
  • Spring Boot 与 Ollama 集成部署私有LLM服务 的完整避坑指南,涵盖 环境配置、模型管理、性能优化 和 安全加固
  • 【数据结构入门】数组和链表的OJ题(2)
  • uv与conda环境冲突,无法使用uv环境,安装包之后出现ModuleNotFoundError: No module named ‘xxx‘等解决方法
  • SpringBoot中策略模式使用
  • tcp 确认应答和超时时间
  • mq_timedsend系统调用及示例
  • Lua语言程序设计1:基础知识、数值、字符串与表
  • DDOS攻击和CC攻击对服务器的伤害有哪些?
  • 蘑兔音乐:音乐创作的神奇钥匙​
  • AI产品经理手册(Ch9-11)AI Product Manager‘s Handbook学习笔记
  • Linux系统交叉编译:依赖、构建与实践
  • makefile的使用与双向链表
  • 使用YOLOv8-gpu训练自己的数据集并预测
  • 多传感器融合
  • 2025暑期作业
  • 企业如何用现代数仓架构挖掘新业务盈利点?AllData产品从目标、路径、结果给出答案
  • 分布式文件系统06-分布式中间件弹性扩容与rebalance冲平衡
  • 集成学习与随机森林:从原理到实践指南
  • 解决VScode无法打开本地文件夹及远程连接后无反应的问题
  • Maven和Gradle在构建项目上的区别
  • 范式集团与海博思创成立合资公司,杀入“AI+储能”赛道