POJ 3260-The Fewest Coins-混合背包+二进制优化

Farmer John has gone to town to buy some farm supplies. Being a very efficient man, he always pays for his goods in such a way that the smallest number of coins changes hands, i.e., the number of coins he uses to pay plus the number of coins he receives in change is minimized. Help him to determine what this minimum number is.

FJ wants to buy T (1 ≤ T ≤ 10,000) cents of supplies. The currency system has N (1 ≤ N ≤ 100) different coins, with values V1, V2, …, VN (1 ≤ Vi ≤ 120). Farmer John is carrying C1 coins of value V1, C2 coins of value V2, …, and CN coins of value VN (0 ≤ Ci ≤ 10,000). The shopkeeper has an unlimited supply of all the coins, and always makes change in the most efficient manner (although Farmer John must be sure to pay in a way that makes it possible to make the correct change).

Input

Line 1: Two space-separated integers: N and T.
Line 2: N space-separated integers, respectively V1, V2, …, VN coins ( V1, … VN)
Line 3: N space-separated integers, respectively C1, C2, …, CN

Output

Line 1: A line containing a single integer, the minimum number of coins involved in a payment and change-making. If it is impossible for Farmer John to pay and receive exact change, output -1.

Sample Input

3 70
5 25 50
5 2 1

Sample Output

3

题目大意:

买家有几种面值的钱币,每种钱币的数量给定
卖家有同样种类的钱币,每种钱币的数量无限
买家想买价值T的货物,需要付钱,然后卖家找钱。
问付钱和找钱的张数之和最小是多少。

核心思想:

付钱是多重背包,用d1[i]存储。
找钱是完全背包,用d2[i]存储。
付出的钱-找回的钱=T。
T为差值遍历两个dp数组取最少的张数。
for(int i=T;i<=end;i++)ans=min(ans,d1[i]+d2[i-T]);

代码如下:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int N=110,M=1e5+10;
//d1是付钱的多重背包,d2是找钱的完全背包
int v[N],c[N],d1[M],d2[M]; 
int main()
{
	int n,T;
	while(cin>>n>>T)
	{
		int mv=0;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&v[i]);
			mv=max(mv,v[i]);
		}
		//计算用钱上限,也是dp上限 
		int end=T+mv*mv;
		for(int i=1;i<=n;i++)
			scanf("%d",&c[i]);
		//最后要判断dp是否等于inf,赋值不用memset 
		for(int i=1;i<=end;i++)
			d1[i]=d2[i]=inf;
		d1[0]=d2[0]=0;
		//付钱的多重背包 
		for(int i=1;i<=n;i++)
		{
			//j用移位运算,二进制优化
			for(int j=1;j<=c[i];j<<=1) 
			{
				for(int z=end;z>=j*v[i];z--)
					d1[z]=min(d1[z],d1[z-j*v[i]]+j);
				c[i]-=j;
			}
			if(c[i])
			{
				for(int z=end;z>=c[i]*v[i];z--)
					d1[z]=min(d1[z],d1[z-c[i]*v[i]]+c[i]);
			}
		}
		//找钱的完全背包 
		for(int i=1;i<=n;i++)
			for(int z=v[i];z<=end;z++)
				d2[z]=min(d2[z],d2[z-v[i]]+1); 
		int ans=inf;
		//以T为差值遍历两个dp数组取最少的张数
		for(int i=T;i<=end;i++)
			ans=min(ans,d1[i]+d2[i-T]);
		if(ans==inf)
			printf("-1\n");
		else
			printf("%d\n",ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值