HDU--2126 Buy the souvenirs(二维01背包)

题目http://acm.hdu.edu.cn/showproblem.php?pid=2126
分析:有两个要求,一是计算最多可以选多少中纪念品;而是计算选最多纪念品的方案有多少种,
即统计最优方案的个数。dp[j][k]等价于dp[i][j][k]表示在前i个物品中选取j个纪念品花费为k的方案数。
 dp[j][k]=dp[j][k]+dp[j-1][k-c[i]]

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

int n,m,p[35],dp[35][510];

void ZeroOnePack()
{
  memset(dp,0,sizeof(dp));
  dp[0][0]=1;

  for(int i=1;i<=n;i++)
    for(int j=n;j>=1;j--)
      for(int k=m;k>=p[i];k--)
        dp[j][k]+=dp[j-1][k-p[i]];

  int ans;
  for(int j=n;j>=1;j--)
  {
    ans=0;
    for(int k=m;k>=0;k--)
      ans+=dp[j][k];
    if(ans){
      printf("You have %d selection(s) to buy with %d kind(s) of souvenirs. ",ans,j);
      return;
    }
  }
  printf("Sorry, you can't buy anything. ");
}

int main()
{
  int t;
  scanf("%d",&t);
  while (t--)
  {
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
      scanf("%d",&p[i]);

    ZeroOnePack();
  }
  return 0;
}





原文地址:https://www.cnblogs.com/gt123/p/3474682.html