Language:
The Fewest Coins
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 1: Two space-separated integers:
N
and
T.
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
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 Hint
Farmer John pays 75 cents using a 50 cents and a 25 cents coin, and receives a 5 cents coin in change, for a total of 3 coins used in the transaction.
|
第一次做混合背包,john为多重背包,店家为完全背包。
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int inf=1000000000;
int value[110],amount[110];
int dp[34010],dp1[34010];
int n,t;
int mv;
void comp(int cost)
{
for(int i=cost; i<=mv; i++)
dp[i]=min(dp[i],dp[i-cost]+1);
}
void zero(int cost,int num)
{
for(int i=mv; i>=cost; i--)
dp[i]=min(dp[i],dp[i-cost]+num);
}
void mult(int cost,int cnt)
{
if(cnt*cost>=mv)
comp(cost);
else
{
int k=1;
while(k<cnt)
{
zero(k*cost,k);
cnt-=k;
k*=2;
}
zero(cnt*cost,cnt);
}
}
int main()
{
//freopen("in.txt","r",stdin);
while(cin>>n>>t)
{
int m=0;
for(int i=1; i<=n; i++)
{
cin>>value[i];
if(m<value[i])
m=value[i];
}
mv=t+10000;
for(int i=1; i<=n; i++)
cin>>amount[i];
for(int i=1;i<=mv;i++)
dp[i]=dp1[i]=inf;
dp[0]=0;
dp1[0]=0;
for(int i=1; i<=n; i++)
mult(value[i],amount[i]);
for(int i=1; i<=n; i++)
for(int j=value[i]; j<=mv; j++)
dp1[j]=min(dp1[j],dp1[j-value[i]]+1);
int ans=inf;
for(int i=t;i<=mv;i++)
dp[t]=min(dp[t],dp[i]+dp1[i-t]);
if(dp[t]==inf)
cout<<-1<<endl;
else
cout<<dp[t]<<endl;
}
return 0;
}