POJ-3260 The Fewest Coins

The Fewest Coins
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 6615 Accepted: 2039

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 V1, V2, ..., VN coins (V1, ...VN)
Line 3: N space-separated integers, respectively C1, C2, ..., 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

 1 #include<iostream>
 2 #include<string.h>
 3 #include<stdio.h>
 4 #include<algorithm>
 5 #define INF 999999999
 6 using namespace std;
 7 int dp1[20005],dp2[20005];
 8 int main()
 9 {
10     int n,m;
11     while(cin>>n>>m)
12     {
13         memset(dp1,0,sizeof(dp1));
14         memset(dp2,0,sizeof(dp2));
15         int val[150],num[150];
16         for(int i=1;i<=n;i++)
17             cin>>val[i];
18         for(int i=1;i<=n;i++)
19             cin>>num[i];
20         for(int i=1;i<=20000;i++)
21             dp1[i]=dp2[i]=INF;
22         dp1[0]=dp2[0]=0;
23         for(int i=1;i<=n;i++)
24         {
25             for(int k=1,flag=0;;k*=2)
26             {
27                 if(k*2>num[i])
28                 {
29                     k=num[i]-k+1;
30                     flag=1;
31                 }
32                 for(int j=20000;j>=k*val[i];j--)
33                 {
34                     dp1[j]=min(dp1[j],dp1[j-k*val[i]]+k);
35                 }
36                 if(flag)
37                     break;
38             }
39         }
40         for(int i=1;i<=n;i++)
41         {
42             for(int j=val[i];j<=20000;j++)
43                 dp2[j]=min(dp2[j],dp2[j-val[i]]+1);
44         }
45         int ans=INF;
46         for(int i=m;i<=20000;i++)
47         {
48             ans=min(ans,dp1[i]+dp2[i-m]);
49         }
50         if(ans==INF)
51         cout<<-1<<endl;
52         else
53             cout<<ans<<endl;
54     }
55     return 0;
56 }

 



posted @ 2017-07-20 22:56  ISGuXing  阅读(240)  评论(0编辑  收藏  举报