hdu2191 珍惜现在
http://acm.hdu.edu.cn/showproblem.php?pid=2191
DP,部分背包
1 #include <stdio.h> 2 #include <string.h> 3 4 #define N 123 5 6 int n, m; 7 int dp[N], w[N], v[N], num[N]; 8 9 void pack01(int wi, int vi) 10 { 11 int j; 12 for(j=m; j>=wi; j--) 13 { 14 if(dp[j-wi]+vi > dp[j]) 15 { 16 dp[j] = dp[j-wi]+vi; 17 } 18 } 19 } 20 21 void pack(int wi, int vi) 22 { 23 int j; 24 for(j=wi; j<=m; j++) 25 { 26 if(dp[j-wi]+vi > dp[j]) 27 { 28 dp[j] = dp[j-wi]+vi; 29 } 30 } 31 } 32 33 int main() 34 { 35 int t, i, k; 36 scanf("%d", &t); 37 while(t-- && scanf("%d%d", &m, &n)) 38 { 39 for(i=1; i<=n; i++) 40 { 41 scanf("%d%d%d", w+i, v+i, num+i); 42 } 43 memset(dp, 0, sizeof(dp)); 44 for(i=1; i<=n; i++) 45 { 46 if(w[i]*num[i] >= m) 47 { 48 pack(w[i], v[i]); 49 continue; 50 } 51 for(k=1; k<num[i]; k<<=1) 52 { 53 pack01(w[i]*k, v[i]*k); 54 num[i] -= k; 55 } 56 pack01(w[i]*num[i], v[i]*num[i]); 57 } 58 printf("%d\n", dp[m]); 59 } 60 return 0; 61 }