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 ≤
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;
}