http://lightoj.com/volume_showproblem.php?problem=1233
一维多重背包二进制优化的思考:先看这个问题,100=1+2+4+8+16+32+37,观察可以得出100以内任何一个数都可以由以上7个数选择组合得到,所以对物品数目就不是从0都100遍历,而是0,1,2,4,5,16,32,37遍历,时间大大优化。
In a strange shop there are n types of coins of value A1, A2 ... An. C1, C2, ... Cn denote the number of coins of value A1, A2 ... An respectively. You have to find the number of different values (from 1 to m), which can be produced using these coins.
Input
Input starts with an integer T (≤ 20), denoting the number of test cases.
Each case starts with a line containing two integers n (1 ≤ n ≤ 100), m (0 ≤ m ≤ 105). The next line contains 2n integers, denoting A1, A2 ... An, C1, C2 ... Cn (1 ≤ Ai ≤ 105, 1 ≤ Ci ≤ 1000). All Ai will be distinct.
Output
For each case, print the case number and the result.
Sample Input |
Output for Sample Input |
2 3 10 1 2 4 2 1 1 2 5 1 4 2 1 |
Case 1: 8 Case 2: 4 |
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cstdio> 6 #include <vector> 7 #include <ctime> 8 #include <queue> 9 #include <list> 10 #include <set> 11 #include <map> 12 using namespace std; 13 #define INF 0x3f3f3f3f 14 typedef long long LL; 15 const int N = 1e5 + 5; 16 int dp[N]; 17 int val[105], c[105]; 18 19 int main() 20 { 21 int t, n, m; 22 scanf("%d", &t); 23 for(int ca = 1; ca <= t; ++ca) { 24 scanf("%d %d", &n, &m); 25 for(int i = 1; i <= n; ++i) { 26 scanf("%d", val + i); 27 } 28 for(int i = 1; i <= n; ++i) { 29 scanf("%d", c + i); 30 } 31 memset(dp, 0, sizeof(dp)); 32 dp[0] = 1; 33 for(int i = 1; i <= n; ++i) { 34 for(int k = 1; k <= c[i]; k <<= 1) { 35 for(int j = m; j >= k*val[i]; --j) { 36 dp[j] |= dp[j - k*val[i]]; 37 } 38 c[i] -= k; 39 } 40 if(c[i]) { 41 for(int j = m; j >= c[i]*val[i]; --j) { 42 dp[j] |= dp[j - c[i]*val[i]]; 43 } 44 } 45 } 46 int ans = 0; 47 for(int i = 1; i <= m; ++i) { 48 ans += dp[i]; 49 } 50 printf("Case %d: %d ", ca, ans); 51 } 52 return 0; 53 }