HDU 2844: Coins【01背包的二进制优化】

HDU 2844: Coins

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

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

题意

题目给出数据数量n和所求价值上限m,并在一行内给出硬币价值A1,A2,A3,......,An以及对应数目C1,C2,C3,......,Cn,要求输出1-m元内可以用所给硬币拼出的价格数量。

思路

多重背包问题,转为01背包用二进制优化。需要注意的是背包大小和待求价值都是钱,二进制优化后没有“体积”一说,打表时需要多注意。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <vector>

using namespace std;

int dp[200000];

//vector<int>tvalue;
int tvalue[101];
//vector<int>value;
int value[200000];

int main()
{
	int n, m;
	scanf("%d%d", &n, &m);
	while(n||m)
	{
		int i, va, nu;
		//value.push_back(0);
		int s = 1;
		for (i = 0; i < 2 * n; i++)
		{
			if (i < n)
			{
				//scanf("%d", &va);
				//tvalue.push_back(va);
				scanf("%d", &tvalue[i]);
			}
			else
			{
				scanf("%d", &nu);

				//二进制优化

				for (int j = 1; j <= nu; j <<= 1)
				{
					nu -= j;
					//value.push_back(j*tvalue[i - n]);
					value[s] = j * tvalue[i - n];
					s++;
				}
				if (nu)
				{
					//value.push_back(nu*tvalue[i - n]);
					value[s] = nu * tvalue[i - n];
					s++;
				}
			}
		}
		vector<int>::iterator vpos, npos;

		//背包打表

		memset(dp, 0, sizeof(int) * 200000);
		//for (i = 0; i < value.size(); i++)
		for (i = 0; i < s; i++)
		{
			for(int j = m; j >= value[i]; j--)
			{
				//注意此处背包容量也是钱,不能用硬币的数目num[i]
				if (dp[j] < dp[j - value[i]] + value[i])//错误:dp[j]<dp[j-num[i]]+value[i];
					dp[j] = dp[j - value[i]] + value[i];
			}
		}
		//dp[j]为考虑了所有硬币后,当背包容量(想要凑出的钱)为j时的最大价值
		//如果当前容量i与在当前容量内所能凑得的最大价值dp[i]相等,则此为所能支付的钱款。

		int count = 0;
		for (i = 1; i <= m; i++)//错误:for(i=1;i< num.size();i++)
		{
			if (dp[i] == i)count++;
		}
		printf("%d\n", count);
		scanf("%d%d", &n, &m);
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/x948675238/article/details/81153673