POJ3260-The Fewest Coins

http://poj.org/problem?id=3260

#include<cstdio>
#include<cstring>
#include<algorithm>
#define INF 1<<29
using namespace std;
int T,N,V[1001],C[1001],buy[40000],sell[40000],i,j,k,maxv,ans;
int main(void)
{
    while(scanf("%d%d",&N,&T)!=EOF)
    {
        maxv=0;
        for(i=1;i<=N;i++)
        {
            scanf("%d",&V[i]);
            maxv=max(maxv,V[i]);
        }
        for(i=1;i<=N;i++)
           scanf("%d",&C[i]);
        maxv=maxv*maxv+T+1;
        fill(buy,buy+maxv+1,INF);
        buy[0]=0;
        for(i=1;i<=N;i++)
           if(C[i]*V[i]>=maxv)
           {
                  for(j=V[i];j<=maxv;j++)
                  buy[j]=min(buy[j],buy[j-V[i]]+1);
           }
           else
           {
                  k=1;
               while(k<C[i])
               {
                      for(j=maxv;j>=V[i]*k;j--)
                      buy[j]=min(buy[j],buy[j-V[i]*k]+k);
                   C[i]-=k;
                   k*=2;
               }
               for(j=maxv;j>=V[i]*C[i];j--)
                  buy[j]=min(buy[j],buy[j-V[i]*C[i]]+C[i]);
           }
        fill(sell,sell+maxv+1,INF);
        sell[0]=0;
        for(i=1;i<=N;i++)
           for(j=V[i];j<=maxv;j++)
              sell[j]=min(sell[j],sell[j-V[i]]+1);
        ans=INF;
        for(i=0;i<=maxv-T;i++)
           ans=min(ans,buy[i+T]+sell[i]);
        if(ans==INF)
           ans=-1;
        printf("%d\n",ans);
    }
    return 0;
}
posted @ 2012-08-31 10:26  Yogurt Shen  阅读(220)  评论(0编辑  收藏  举报