首页 > 代码库 > HDU 2844 Coins (动规)

HDU 2844 Coins (动规)

Coins

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6904    Accepted Submission(s): 2809



Problem Description
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.
 

Input
The 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.
 

Output
For 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
 

Source
2009 Multi-University Training Contest 3 - Host by WHU
 

Recommend
gaojie   |   We have carefully selected several similar problems for you:  2845 2191 2870 2577 2830

这是一道好题!刚开始用原始的多重背包去写总是超时,后来听说可以用二进制去优化的,就去査了一下资料,才A掉的!~
题意:
    给你一个一些银币的面值和对应的个数, 然后给一个数m,问从1到m这些数有多少个能用现有的硬币来表示。

    比较单纯的多重背包,用二进制去优化硬币对饮的面值就行了。然后对包进行判断有多少个符合 b[i] == i即可;

a[i]表示钱币的价值,b[i]表示钱币的数量。

#include <iostream>
#include <algorithm>
using namespace std;
#define M 100005
int dp[M],vis[M];   //想用01背包做,果断超时。。。
int a[105],b[105];
int n,tot,m;
int max(int x,int y)
{
    return x>y?x:y;
} 
//百度所得,膜拜。
void CompletePack(int cost,int weight)     //如果取不完就是完全背包。
{  
    for(int i=cost;i<=m;i++)  
    dp[i]=max(dp[i],dp[i-cost]+weight);  
}  
void ZeroOnePack(int cost,int weight)      //如果能取完就是01背包。
{  
    for(int i=m;i>=cost;i--)  
    dp[i]=max(dp[i],dp[i-cost]+weight);  
}  
void MultiplyPack(int cost,int weight,int amount)  //多重背包。
{  
    if(cost*amount>=m)                             //取不完。
    CompletePack(cost,weight);  
    else  
    {  
    int k=1;                                      
    while(k<amount)  
    {  
        ZeroOnePack(k*cost,k*weight);           //传说中的二进制优化,表示没明白。我觉得就是一次取1,2,4,8。。。枚钱币,倍增的思想。
        amount-=k;  
        k<<=1;  
    }  
    ZeroOnePack(amount*cost,amount*weight);    //这里把剩下的再算上去。
    }  
}  
int main(int i,int j,int k)
{    

    while(scanf("%d%d",&n,&m)!=EOF&&n&&m)
    {   
        tot=k=0;
        for(i=1;i<=n;i++)  scanf("%d",&a[i]);
        for(i=1;i<=n;i++)  scanf("%d",&b[i]);
        memset(dp,0,sizeof(dp));
            for(i=1;i<=n;i++)    
             MultiplyPack(a[i],a[i],b[i]);
                for(i=1;i<=m;i++)    if(dp[i]==i) tot++;                    
                printf("%d\n",tot);
    }
    return 0;
}