HDU-3591 混合背包
The trouble of Xiaoqian
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2277 Accepted Submission(s): 805Problem DescriptionIn 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.InputThere 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.OutputOutput 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 Input3 705 25 505 2 10 0Sample OutputCase 1: 3
题目大意就是小倩付多少钱才会有交换的硬币次数最少。
这是一道混合背包题目,小倩的硬币是多重背包,售货员的是完全背包。因为不会超过20000元;那么遍历就好了
AC代码:
1 #include<iostream>
2 #include<stdio.h>
3 #include<algorithm>
4 #include<string.h>
5 #include<string>
6 #define INF 9999999
7 #include<algorithm>
8 using namespace std;
9 int dp1[20005],dp2[20005];
10 int val[150],num[150];
11 int min(int x,int y)
12 {
13 return x>y? y:x;
14 }
15 int main()
16 {
17 int n,m;
18 int T=1;
19 while(cin>>n>>m)
20 {
21 if(n==0&&m==0) break;
22 for(int i=1;i<=n;i++)
23 cin>>val[i];
24 for(int i=1;i<=n;i++)
25 cin>>num[i];
26 for(int i=1;i<=20000;i++)
27 dp1[i]=dp2[i]=INF;
28 dp1[0]=dp2[0]=0;
29 for(int i=1;i<=n;i++)//多重背包
30 {
31 for(int k=1,flag=0;;k*=2)
32 {
33 if(k*2>num[i])
34 {
35 k=num[i]-k+1;
36 flag=1;
37 }
38 for(int j=20000;j>=k*val[i];j--)
39 {
40 dp1[j]=min(dp1[j],dp1[j-k*val[i]]+k);
41 }
42 if(flag)
43 break;
44 }
45 }
46 for(int i=1;i<=n;i++)//完全背包,这里有两种写法,一种是这种常规的优化了的,还有一种适合新手,虽然复杂度会高些,但是新手理解起来会更容易。
47 {
48 for(int j=val[i];j<=20000;j++)49 dp2[j]=min(dp2[j],dp2[j-val[i]]+1);
50 }
/*
for(int i=1;i<=n;i++)
{
for(int k=1;k*val[i]<20000;k*=2)//类比于多重背包
{
for(int j=20000;j>=k*val[i];j--)
{
dp2[j]=min(dp2[j],dp2[j-k*val[i]]+k);
}
}
}
*/
51 int lss=INF; 52 for(int i=m;i<=20000;i++) 53 { 54 lss=min(lss,dp1[i]+dp2[i-m]); 55 } 56 if(lss>20000) 57 cout<<"Case "<<T++<<": "<<-1<<endl; 58 else 59 cout<<"Case "<<T++<<": "<<lss<<endl; 60 } 61 return 0; 62 }