The Fewest Coins

Problem 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: <i>N</i> and <i>T</i>. <br>Line 2: N space-separated integers, respectively <i>V</i><sub>1</sub>, <i>V</i><sub>2</sub>, ..., <i>V<sub>N</sub></i> coins (<i>V</i><sub>1</sub>, ...<i>V<sub>N</sub></i>) <br>Line 3: N space-separated integers, respectively <i>C</i><sub>1</sub>, <i>C</i><sub>2</sub>, ..., <i>C<sub>N</sub></i>

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

顾客多重背包,加二进制优化,店主完全背包

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define inf 0x3f3f3f3f
int c[105],v[105];
int p[30000]={0};
int q[30000]={0};
int dp1[25020];
int dp2[25020];
int n,t,top=0,ans=0,vm=-1,mx;
using namespace std;
int main()
{
    memset(dp1,inf,sizeof(dp1));
    memset(dp2,inf,sizeof(dp2));
    dp1[0]=0;
    dp2[0]=0;
    scanf("%d%d",&n,&t);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&v[i]);
        vm=max(vm,v[i]);
    }
    mx=vm*vm+t;
    for(int i=0;i<n;i++)
    {
        scanf("%d",&c[i]);
    }
    for(int i=0;i<n;i++)
    {
        for(int j=1;j<=c[i];j*=2)
        {
            p[top]=j*v[i];
            q[top]=j;
            c[i]-=j;
            top++;
        }

    if(c[i]>0)
    {
        p[top]=c[i]*v[i];
        q[top]=c[i];
        top++;
    }
}
for(int i=0;i<top;i++)
for(int j=mx;j>=p[i];j--)
dp1[j]=min(dp1[j],dp1[j-p[i]]+q[i]);
for(int i=0;i<n;i++)
for(int j=v[i];j<=mx;j++)
dp2[j]=min(dp2[j],dp2[j-v[i]]+1);
int ans=inf;
for(int i=t;i<=mx;i++)
ans=min(ans,dp1[i]+dp2[i-t]);
if(ans==inf)
printf("-1\n");
else

printf("%d\n",ans);
return 0;
}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/81253287
今日推荐