Bessie is not so good at combinatorics. Determine the optimal combination of feed buckets that gives Bessie as many calories without exceeding the limit C.
As an example, consider a limit of 40 calories and 6 buckets with 7, 13, 17, 19, 29, and 31 calories. Bessie could eat 7 + 31 = 38 calories but could eat even more by consuming three buckets: 7 + 13 + 19 = 39 calories. She can find no better combination.
Input
* Line 1: Two space-separated integers: C and B* Line 2: B space-separated integers that respectively name the number of calories in bucket 1, 2, etc.
Output
* Line 1: A single line with a single integer that is largest number of calories Bessie can consume and still stay on her diet.Sample Input
40 6 7 13 17 19 29 31
Sample Output
39
注意dp数组的初始化,状态方程:
for i=1..N
forv=V..0
f[v]=max{f[v],f[v-c[i]]+w[i]};
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
int main(){
int V,n;
int w[25],dp[35005];
scanf("%d%d",&V,&n);
for (int i = 0;i < n;i++) scanf("%d",&w[i]);
memset(dp,0,sizeof(dp));
for (int i = 0;i < n;i++){
for (int j = V;j >= w[i];j--){
dp[j] = max(dp[j],dp[j-w[i]]+w[i]);
}
}
printf("%d\n",dp[V]);
return 0;
}