您的位置:首页 > 其它

【多重背包】HDU2844Coins【模板】

2016-04-07 17:33 288 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2844

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

代码:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
const int N=100000;
int w
,k
,dp
;
int n,m;
void ZeroOnePack(int cost,int weight) // 01 价值,重量;
{
for(int i=m;i>=weight;i--)
dp[i]=max(dp[i],dp[i-weight]+cost);
}
void CompletePack(int cost,int weight) // 完全
{
for(int i=weight;i<=m;i++) // 天啦,写成i>=m,结果郁闷了一下午。。。
dp[i]=max(dp[i],dp[i-weight]+cost);
}
void MultiplePack(int cost,int weight,int cnt) // 价值,重量,数量;
{
if(m<=cnt*cost){ // 该物品足够装满背包,相当于可以去无限次;
CompletePack(cost,weight);
return ;
}else{ // 否则,转换成01背包;
int k=1;
while(k<=cnt){
ZeroOnePack(k*cost,k*weight);
cnt=cnt-k;
k=2*k; // 1 2 4 8 16;二进制计数,提高效率;
}
ZeroOnePack(cnt*cost,cnt*weight); // 将最后可能没有判断的再惊醒一次判断;
}
}
int main()
{
cin.sync_with_stdio(false);
while(cin>>n>>m&&n&&m){
for(int i=0;i<n;i++) cin>>w[i]; // 表示重量和价值;
for(int i=0;i<n;i++) cin>>k[i]; // 表示数量;
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++)
MultiplePack(w[i],w[i],k[i]);
int cnt=0;
for(int i=1;i<=m;i++)
if(dp[i]==i) cnt++; // 重量和价值等价;
cout<<cnt<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: