HDU-3591-The trouble of Xiaoqiant

来源:互联网 发布:苏州德威国际学校 知乎 编辑:程序博客网 时间:2024/06/01 10:43

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3591

The trouble of Xiaoqian

Problem Description
In the country of ALPC , Xiaoqian is a very famous mathematician. She is immersed in calculate, and she want to use the minimum number of coins in every shopping. (The numbers of the shopping include the coins she gave the store and the store backed to her.)
And now , Xiaoqian wants to buy T (1 ≤ T ≤ 10,000) cents of supplies. The currency system has N (1 ≤ N ≤ 100) different coins, with values V1, V2, ..., VN (1 ≤ Vi ≤ 120). Xiaoqian is carrying C1 coins of value V1, C2 coins of value V2, ...., and CN coins of value VN (0 ≤ Ci ≤ 10,000). The shopkeeper has an unlimited supply of all the coins, and always makes change in the most efficient manner .But Xiaoqian is a low-pitched girl , she wouldn’t like giving out more than 20000 once.
 

Input
There are several test cases in the input.
Line 1: Two space-separated integers: N and T. 
Line 2: N space-separated integers, respectively V1, V2, ..., VN coins (V1, ...VN) 
Line 3: N space-separated integers, respectively C1, C2, ..., CN
The end of the input is a double 0.
 

Output
Output one line for each test case like this ”Case X: Y” : X presents the Xth test case and Y presents the minimum number of coins . If it is impossible to pay and receive exact change, output -1.
 

Sample Input
3 705 25 505 2 10 0
 

Sample Output
Case 1: 3

题目分析:

 n种不同的硬币,价值为value[n],每种硬币的数量为为num[n],问如何付 钱,交易的钱币个数最少(他给售货员的硬币数目+售货员找他的)
人所带的各种硬币的个数是有限的,故多重背包,售货员则用完全背包。求最小值,则将dp初始化为无穷大。
注意背包的容量是20000,而不是输入的t。 

代码如下:

#include<cstdio>#include<cstring>#include<iostream>using namespace std ;const int inf=99999;const int maxx=20000;int dp1[inf],dp2[inf],num[130],cost[130];int main(){    int n,t,i,j,k;    int cas=1;     while(cin>>n>>t)    {        if(n==0&&t==0)        break;        for(i=1;i<=n;i++)        cin>>cost[i];        for(i=1;i<=n;i++)        cin>>num[i];        for(i=1;i<=inf;i++)        dp1[i]=dp2[i]=inf;        dp1[0]=dp2[0] = 0 ;        for(i=1;i<=n;i++)        {            for(j=cost[i];j<=maxx;j++)            {                dp2[j]=min(dp2[j],dp2[j-cost[i]]+1);            }        }         for(i=1;i<=n;i++)        {            for(j=1;j<=num[i];j*=2)            {                for(k=maxx;k>=j*cost[i];k--)                {                    dp1[k]=min(dp1[k],dp1[k-j*cost[i]]+j);                }                num[i]-=j;            }            if(num[i])            {                for(k=maxx;k>=num[i]*cost[i];k--)                {                    dp1[k]=min(dp1[k],dp1[k-num[i]*cost[i]]+num[i]);                }            }        }        int ans=inf;        for(i=t;i<=maxx;i++)        {            ans=min(ans,dp1[i]+dp2[i-t]);        }        if(ans==inf)        ans=-1;        cout<<"Case "<<cas++<<": "<<ans<<endl;    }    return 0;}


原创粉丝点击