POJ - 1787 完全背包,记录路径

题意:你有1,5,10,25四种硬币数量有限,你想买价格为p的咖啡,问你能不能购买,要求花的硬币尽量多,并且输出每种硬币花了多少;
思路:看起来像多重背包加记录路径但用完全背包比较好写

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXN 33000
#define INF 0x3f3f3f3f
#define lmid l,m,rt<<1
#define rmid m+1,r,rt<<1|1
#define ls rt<<1
#define rs rt<<1|1
#define Mod 1000000007
#define i64 __int64
#define LIMIT_ULL 100000000000000000
using namespace std;
int dp[10005];
int a[10005][4];
int s[4];
int t[4]={1,5,10,25};
int main()
{
     int n;
     while(scanf("%d",&n)==1)
     {
          memset(dp,-1,sizeof(dp));
          memset(a,0,sizeof(a));
          for(int i=0;i<4;i++)
          {
               scanf("%d",&s[i]);
          }
          if(n==0&&s[0]==0&&s[1]==0&&s[2]==0&&s[3]==0)
               break;
          dp[0]=0;
          for(int i=0;i<4;i++)
               for(int j=t[i];j<=n;j++)
          {
               if(dp[j-t[i]]!=-1)
               {
                    if(dp[j]1&&a[j-t[i]][i]+1<=s[i])
                    {
                         dp[j]=dp[j-t[i]]+1;
                         for(int k=0;k<4;k++)
                              a[j][k]=a[j-t[i]][k];
                         a[j][i]++;
                    }
               }
          }
          if(dp[n]==-1)
          {
               cout<<"Charlie cannot buy coffee."<continue;
          }
          printf("Throw in %d cents, %d nickels, %d dimes, and %d quarters.\n",a[n][0],a[n][1],a[n][2],a[n][3]);
     }
     return 0;
}

你可能感兴趣的:(DP)