【FZU - 1432】Coin Changing(多重背包+装满)

There are n kinds of coins. Given the available number of coins for each kind, you are to calculate the minimal number of coins needed to exchange m yuan. 
 

Input

There are several test cases. The fist line of each case contains an integer n (1<=n<=10). Followed n lines, each line contains two integers representing the cost and the available number of coins of this kind respectively. The last line of each case contains an integer m (1<=m<=20001) representing the given amount of money you have to exchange. 
 

Output

Please output the minimal number of coins needed to exchange the money. If you can't exchange the given amount of money, please output -1. 

Sample Input

3
1 3
2 3
5 3
18

Sample Output

5

解题报告:

多重背包+要求装满的问题,这里的成本可以看成以前常写的背包的体积,数量经过二进制优化以后就可以看做价值,这道题就可以转化成,在背包完全装满的前提下,求最小的体积,注意一下初始化就好。

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<cstring>
#define inf 0x3f3f3f3f
using namespace std;
int w[10000];
int a[300000];
int num[300000];
int dp[300000];
int main()
{
	int n;
	while(~scanf("%d",&n))//这里没加~ T了,有时也可能报输出过多?? 加上然后wa了。。后面输出的问题 
	{
		memset(dp,inf,sizeof(dp));
		dp[0]=0;
		int tt=0;
		int c;
		for(int i=0;i<n;i++)
		{
			scanf("%d%d",&w[i],&c);
			for(int k=1;k<=c;k<<=1)
			{
				num[tt]=k;
				a[tt++]=k*w[i];
				c-=k;
			 } 
			 if(c>0)
			 {
			 	num[tt]=c;
			 	a[tt++]=c*w[i];
			 }
		}
		int m;
		scanf("%d",&m);
		for(int i=0;i<tt;i++)
		{
			for(int j=m;j>=a[i];j--)
			{
				dp[j]=min(dp[j],dp[j-a[i]]+num[i]);
			}
		}
		if(dp[m]==inf)//题目没读全,少了一半输出。。。。 
		printf("-1\n");
		else 
		printf("%d\n",dp[m]);
	}
	
	
 } 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值