POJ1742 Coins 背包

题目大意:给出一些钱币的价值和对应的数目,求在一定价值限定下这些钱币能凑成的价值数。

本题用多重背包直接拆分或二进制拆分法都太慢。说起处理一组物品,完全背包可算是比较效率高的,但是本题中物体的数目是有限的呀!因此我们可以对于每一个物品(钱币)i设置一个used数组,used[j]表示在凑成价值j的各个钱币中,需要钱币i的数量是多少。vis是价值是否能够凑成的数组。

只有当:

  • vis[j]==false(如果价值j已经被其它钱币所凑成,则把当前的i钱币用于凑成以后的价值可能性会更高)
  • vis[j-a[i]]==true(把价值j-a[i]凑成了以后才能凑成j)
  • used[j-a[i]]<num[i](表示要凑成价值j,当前钱币i要有剩余)

才更新,并将used[j]++。

#include <cstdio>
#include <cstring>
using namespace std;

const int MAX_OBJ = 1000, MAX_V = 110000, MAX_TYPE = 200;

int Proceed(int totV, int totType, int *num, int *val)
{
	static bool vis[MAX_V];
	static int used[MAX_V];
	memset(vis, 0, sizeof(vis));
	vis[0] = 1;
	for (int i = 1; i <= totType; i++)
	{
		memset(used, 0, sizeof(used));
		for (int j = val[i]; j <= totV; j++)
		{
			if (!vis[j] && vis[j - val[i]] && used[j - val[i]] < num[i])
			{
				vis[j] = true;
				used[j] = used[j - val[i]] + 1;
			}
		}
	}
	int ans = 0;
	for (int i = 1; i <= totV; i++)
		ans += vis[i];
	return ans;
}

int main()
{
#ifdef _DEBUG
	freopen("c:\noi\source\input.txt", "r", stdin);
#endif
	int totType, totV;
	static int val[MAX_TYPE], num[MAX_TYPE];
	while (scanf("%d%d", &totType, &totV) && (totType || totV))
	{
		for (int i = 1; i <= totType; i++)
			scanf("%d", i + val);
		for (int i = 1; i <= totType; i++)
			scanf("%d", i + num);
		printf("%d
", Proceed(totV, totType, num, val));
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/headboy2002/p/8525300.html