POJ1787-Charlie's Change

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

#include<stdio.h>
#include<string.h>
int C[4],ans[30],p[10010],vis[10010],dp[10010],T[4]={1,5,10,25};
int main(void)
{
    int m,i,j,sum;
    while(scanf("%d",&m)!=EOF)
    {
        sum=m;
        for(i=0;i<4;i++)
        {
            scanf("%d",&C[i]);
            sum+=C[i];
        }
        if(sum==0) 
           break;
        memset(dp,0,sizeof(dp));
        memset(p,0,sizeof(p));
        p[0]=-1;
        dp[0]=1;
        for(i=0;i<4;i++)
        {
            memset(vis,0,sizeof(vis));
            for(j=T[i];j<=m;j++)
              if((!dp[j]||dp[j-T[i]]+1>dp[j])&&dp[j-T[i]]&&vis[j-T[i]]<C[i])
              {
                  dp[j]=dp[j-T[i]]+1;
                  vis[j]=vis[j-T[i]]+1;
                  p[j]=j-T[i];
              }
        }
        memset(ans,0,sizeof(ans));
        if(dp[m])
        {
             i=m;
             while(1)
             {
                 if(p[i]==-1) 
                    break;
                 ans[i-p[i]]++;
                 i=p[i];
             }
             printf("Throw in %d cents, %d nickels, %d dimes, and %d quarters.\n",ans[1],ans[5],ans[10],ans[25]);
        }
        else printf("Charlie cannot buy coffee.\n");
    }
    return 0;
}
posted @ 2012-08-31 10:39  Yogurt Shen  阅读(315)  评论(0编辑  收藏  举报