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]);
}
}