1. 程式人生 > >【背包專題】 D - Coins hdu2844【多重背包】

【背包專題】 D - Coins hdu2844【多重背包】

write out hello last pan ack som respond 相等

Whuacmers use coins.They have coins of value A1,A2,A3...An Silverland dollar. One day Hibix opened purse and found there were some coins. He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn‘t know the exact price of the watch.

You are to write a program which reads n,m,A1,A2,A3...An and C1,C2,C3...Cn corresponding to the number of Tony‘s coins of value A1,A2,A3...An then calculate how many prices(form 1 to m) Tony can pay use these coins.

InputThe input contains several test cases. The first line of each test case contains two integers n(1 ≤ n ≤ 100),m(m ≤ 100000).The second line contains 2n integers, denoting A1,A2,A3...An,C1,C2,C3...Cn (1 ≤ Ai ≤ 100000,1 ≤ Ci ≤ 1000). The last test case is followed by two zeros.OutputFor each test case output the answer on a single line.Sample Input

3 10
1 2 4 2 1 1
2 5
1 4 2 1
0 0

Sample Output

8
4


題意:問能夠將輸入的錢幣組合為1~m之間的數的種類總數,比如樣例2:m=5,錢幣可以組合為:1,2,4,5.所以總的種類數為4.
思路:在這道題中我們可以把一定數量組合而成的錢幣總價值(1~m)看多背包費用和價值,最後判斷費用和價值相等即記入總數。
還可以把每種錢幣對應的每個數量計算出來,當作01背包來寫這道題:http://blog.csdn.net/hello_sheep/article/details/77581462
#include<stdio.h>
#include
<string.h> #include<algorithm> using namespace std; #define N 100010 int dp[N],value[110],num[110]; int n,m,ans; void CompletePack(int value,int cost) { int i; for(i = cost; i <= m; i ++) dp[i] = max(dp[i],dp[i-cost]+value); return; } void ZeroOnePack(int value,int cost) { int i; for(i = m; i >= cost; i --) dp[i] = max(dp[i],dp[i-cost]+value); return; } void MultiplePack(int num,int value,int cost) { int k; if(value*num > m) CompletePack(value,cost); else { k = 1; while(k < num) { ZeroOnePack(k*value,k*cost); num -= k; k*=2;//為什麽用左移運算符就tle!! } if(num) ZeroOnePack(num*value,num*cost); } return; } int main() { int i,j; while(scanf("%d%d",&n,&m),m+n) { memset(dp,0,sizeof(dp)); for(i = 1; i <= n; i ++) scanf("%d",&value[i]); for(i = 1; i <= n; i ++) scanf("%d",&num[i]); for(i = 1; i <= n; i ++) MultiplePack(num[i],value[i],value[i]); ans = 0; for(i = 1; i <= m; i ++) if(dp[i] == i)//費用和價值相等,滿足條件 ans++; printf("%d\n",ans); } return 0; }



【背包專題】 D - Coins hdu2844【多重背包】