如题:http://poj.org/problem?id=3260
Description
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 2: N space-separated integers, respectively V 1, V 2, ..., VN coins ( V 1, ... VN)
Line 3: N space-separated integers, respectively C 1, C 2, ..., CN
Output
Sample Input
3 70 5 25 50 5 2 1
Sample Output
3
要求给出的钱的硬硬币数+找回的硬币数量最少。
老板找零,硬币数量无限制。
也就是多重背包+完全背包。
关键在于背包的容量,到底给多少,如果给出所有硬币总价值的上限则太大。120*10000*100 肯定不行。
背包容量上限v_max*v_max+T.
如果超过这个,找零一定超过v_max*v_max。则一定有至少两种硬币可以组合成若干v_max的硬币(抽屉原理)。因此不是最优,所以最优背包上限v_max*v_max+T。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define inf 0x0fffffff
#define min(a,b)(a<b?a:b)
int mon[103];
int num[103];
int f[120*120+50]; //支付当前金额所用硬币最少数量。
int f1[120*120+50];
int N,T;
void ZeroOnePack(int a[],int k,int v,int c)
{
int j;
for(j=v;j>=k*c;j--)
a[j]=min(a[j],a[j-k*c]+k);
}
void CompletePack(int a[],int v,int c)
{
int j;
for(j=c;j<=v;j++)
a[j]=min(a[j],a[j-c]+1);
}
void MultiplePack(int a[],int v,int c,int cnt)
{
if(c*cnt>=v)
{
CompletePack(a,v,c);
return;
}
int k=1;
while(k<cnt)
{
ZeroOnePack(a,k,v,c);
cnt-=k;
k*=2;
}
ZeroOnePack(a,cnt,v,c);
}
int main()
{
// freopen("C:\\1.txt","r",stdin);
// freopen("C:\\2.txt","w",stdout);
scanf("%d%d",&N,&T);
int i;
int maxv=120*120+T;;
for(i=1;i<=N;i++)
scanf("%d",&mon[i]);
for(i=1;i<=N;i++)
{
scanf("%d",&num[i]);
}
for(i=0;i<maxv+10;i++)
{
f[i]=inf;
f1[i]=inf;
}
f[0]=0;
f1[0]=0;
for(i=1;i<=N;i++)
MultiplePack(f,maxv,mon[i],num[i]);
for(i=1;i<=N;i++)
CompletePack(f1,maxv-T,mon[i]);
int sum=inf;
for(i=T;i<=maxv;i++)
{
if(f[i]!=inf&&f1[i-T]!=inf)
{
if(f[i]+f1[i-T]<sum)
sum=f[i]+f1[i-T];
}
}
if(sum!=inf)
printf("%d\n",sum);
else
printf("-1\n");
return 0;
}