HDU2844-Coins(多重背包+二进制优化+01背包)

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

分析:

题意:
第一行两个数字n和m,然后2*n个数字,前面n个表示硬币的面值,然后后面n个数表示每种硬币的数量,问由这些硬币能表示面值不超过m的有多少种?

解析:
第一次,用了二维来解,结果超时了,然后就想到了二进制优化,转化为01背包(这个方法大牛的背包九讲里面由提法到)!

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 105

using namespace std;

struct node{
	int val,num;
};

node book[N];
int dp[100005];
int value[100005];

int main()
{
	int n,m;
	while(~scanf("%d%d",&n,&m)&&n&&m)
	{
		int sum=0,len=0;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&book[i].val);
		}
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&book[i].num);
		}
		for(int i=1;i<=n;i++)
		{
			int t=1;
			while(book[i].num-t>0)
			{
				value[++len]=t*book[i].val;
				book[i].num-=t;
				t=t<<1;
			}
			value[++len]=book[i].num*book[i].val;
		}
		for(int i=1;i<=len;i++)
		{
			for(int j=m;j>=value[i];j--)
			{
				dp[j]=max(dp[j-value[i]]+value[i],dp[j]);
			}
		}
		for(int i=1;i<=m;i++)
		{
			if(dp[i]==i)
				sum++;
		}
		printf("%d\n",sum);
		memset(dp,0,sizeof(dp));
	}
	return 0;
}
发布了64 篇原创文章 · 获赞 17 · 访问量 879

猜你喜欢

转载自blog.csdn.net/weixin_43357583/article/details/105292434