解题思路:
- 完全背包下加条件,令dpj 表示第i种钱下,容量为j的背包,考虑dpj=0 or dpj−arri=0情况下状态方程:
dpj=min(dpj−arri+1,dpj),(dpj=0,dpj+arri=0)
dpj=(j+arri)÷arri,(dpj−arri=0,(j+arri)modarri=0)
dpj=dpj−arri+1,(dpj=0,dpj−arri=0)
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
int n, aim;
cin>>n>>aim;
vector<int> arr(n+1);
for(int i = 1; i <= n; ++i){
cin>>arr[i];
}
vector<int> dp(aim+1);
for(int i = 1; i <= n; ++i){
for(int j = 0; j <= aim - arr[i]; ++j){
if(dp[j] != 0){
if(dp[j+arr[i]] == 0) dp[j+arr[i]] = dp[j] +1;
else dp[j+arr[i]] = min(dp[j]+1,dp[j+arr[i]]);
}
else if((j+arr[i])%arr[i] == 0) dp[j+arr[i]] = (j+arr[i])/arr[i];
}
}
int ans;
if(dp[aim] > 0 || aim == 0) ans = dp[aim];
else ans = -1;
cout<<ans<<endl;
return 0;
}