Coins HDU - 2844

本文介绍了一个经典的背包问题,旨在找出特定区间内可支付的价格数量。通过使用二进制优化技巧,解决了如何利用不同价值的硬币组合支付价格的问题,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

看到英问题就头疼!!!
这个题目看懂题目,理解题意是我觉得最难的一步!(英语贼烂)
其实这个题目意思就是在这个[1,m]这个区间里面有多少个背包可以装满。
(题意浓缩起来只有这么点,提炼出来真心费力)
这个题目第二难的一部就是进行二进制优化。
(由于本菜鸟刚学DP确实这个对我而言是一个长期理解的过程)
二进制优化:
任何一个数都可以由2的N次方来表示,例如4可以有1,2来表示;
8可以有1,2,4来表示;11可以有1,2,4,8来表示。
 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 #define maxn 100010
 7 int dp[maxn],a[105],b[105];
 8 int main()
 9 {
10     int n,m;
11     while(scanf("%d%d",&n,&m)!=EOF){
12         if (n==0 && m==0) break;
13         memset(dp,0,sizeof(dp));
14         for (int i=1 ;i<=n ;i++)
15             scanf("%d",&a[i]);
16         for (int i=1 ;i<=n ;i++)
17             scanf("%d",&b[i]);
18         for (int i=1 ;i<=n ;i++){
19             if (a[i]*b[i]>m) {
20                 for (int k=0;k<=m ;k++){
21                     if (k>=a[i]) dp[k]=max(dp[k],dp[k-a[i]]+a[i]);
22                 }
23             }else {
24                 for (int j=1 ;j<=b[i] ;j=j*2){
25                     for (int k=m ; k>=a[i]*j ;k--){
26                         dp[k]=max(dp[k],dp[k-a[i]*j]+a[i]*j);
27                     }
28                     b[i]-=j;
29                 }
30                 if (b[i]>0) {
31                      for (int k=m ;k>=a[i]*b[i] ;k--) {
32                          dp[k]=max(dp[k],dp[k-a[i]*b[i]]+a[i]*b[i]);
33                      }
34                 }
35             }
36         }
37         int sum=0;
38         for (int i=1 ;i<=m ;i++){
39             if (dp[i]==i) sum++;
40         }
41         printf("%d\n",sum);
42     }
43     return 0;
44 }
View Code

 

转载于:https://www.cnblogs.com/qldabiaoge/p/8505041.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值