POJ3260The Fewest Coins题解动态规划DP

The Fewest Coins
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 1677   Accepted: 444

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.

Source

USACO 2006 December Gold
顾客付钱是多重背包用二进制压缩成01背包
店主找零是完全背包
付钱范围刚开始写t+max(v[i]),t+sum(v[i])都是WA
改成t+v[n]*v[n]/k    (1<=k<=4)才AC
#include<cstdio> #define min(a,b) ((a)<(b)?(a):(b)) int n,t,v[105],c[105]; int DP3(int V) { int m=1,ans=1<<20,i,j,k,ww[1005],vv[1005],tt[20005]={0},d[20005]={0}; for(i=0;i<=V;i++)d[i]=tt[i]=1<<20; for(i=1;i<=n;i++) { k=1; j=c[i]; while(j>=k) { j-=k; ww[m]=k; vv[m++]=v[i]*k; k<<=1; } if(j) { ww[m]=j; vv[m++]=j*v[i]; } } d[0]=tt[0]=0; for(i=1;i<m;i++) for(j=V;j>=vv[i];j--) tt[j]=min(tt[j],tt[j-vv[i]]+ww[i]); for(i=1;i<=n;i++) for(j=v[i];j<=V-t;j++) d[j]=min(d[j],d[j-v[i]]+1); for(i=t;i<=V;i++) ans=min(ans,tt[i]+d[i-t]); if(ans>=1<<20) ans=-1; return ans; } int main() { int i; scanf("%d%d",&n,&t); for(i=1;i<=n;i++) scanf("%d",v+i); for(i=1;i<=n;i++) scanf("%d",c+i); printf("%d/n",DP3(t+v[n]*v[n]/4)); }

你可能感兴趣的:(c,Integer,System,input,output,payment)