poj 3260 hdu 3591 多重背包+完全背包

来源:互联网 发布:sm3算法 编辑:程序博客网 时间:2024/06/08 00:01
The Fewest Coins
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 2618 Accepted: 770

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 V1V2, ..., VN (1 ≤ Vi ≤ 120). Farmer John is carrying C1 coins of value V1C2coins 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 V1V2, ..., VN coins (V1, ...VN
Line 3: N space-separated integers, respectively C1C2, ..., 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 705 25 505 2 1

Sample Output

3
View Code
#include<stdio.h>#include<string.h>const int M = 1200000;const int inf = 1<<30;int V,dpsell[M],dpbuy[M];int num[M],w[M];int  min(int a,int b){return a<b?a:b;}void zero_one(int w,int v){    for(int j=V;j>=w;j--)        dpbuy[j]=min(dpbuy[j-w]+v,dpbuy[j]);}int main(){    int n,t,i,j,ca=1;    while(scanf("%d%d",&n,&t),(n||t))    {        for(i=0;i<n;i++) scanf("%d",&w[i]);        for(i=0;i<n;i++) scanf("%d",&num[i]);        V=10000;        dpsell[0]=0,dpbuy[0]=0;        for(i=1;i<=V;i++)            dpsell[i]=dpbuy[i]=inf;        for(i=0;i<n;i++)//售货员有无穷数量的货币,所以先进行一次完全背包            for(j=w[i];j<=V;j++)                dpsell[j]=min(dpsell[j],dpsell[j-w[i]]+1);        for(i=0;i<n;i++)//顾客每种货币都有一定的数量限制,进行一次多重背包        {            int k=1,count=num[i];            while(k<count)            {                zero_one(k*w[i],k);                count-=k;                k<<=1;            }            zero_one(count*w[i],count);        }        int minn=inf;        for(i=t;i<=V;i++)//判断        {            if(dpbuy[i]!=inf&&dpsell[i-t]!=inf&&dpbuy[i]+dpsell[i-t]<minn)              minn=dpbuy[i]+dpsell[i-t];        }        if(minn==inf) printf("Case %d: -1\n",ca++);        else printf("Case %d: %d\n",ca++,minn);    }}
原创粉丝点击