思路:
要注意的几点:
(1)必须要在N种动漫里面选择M种,所以初始化时dp[L][M]时,除当m=0,dp[L][M]=0外,其他的初始化为负的无穷大;(见背包九讲关于初始化得方法)
(2)最后输出时要满足dp[L][M]不小于0,因为当dp[L][M]<0时,表明不可能在N种动漫里面选择M种(无法完全满足),也是题意:“If DuoDuo can’t watch all of the movies that her uncle had bought for her, please output 0”
AC代码:
#include<stdio.h>
#include<string.h>
#define inf 0x3f3f3f3f
long dp[1005][105],c[105],w[105];
int L,M;
void Bi_ZeroOnePack(int c,int w)
{
int m,l;
for(l=L;l>=c;l--)
for(m=M;m>=1;m--)
if(dp[l][m]<dp[l-c][m-1]+w)
dp[l][m]=dp[l-c][m-1]+w;
}
int main()
{
int n;
int i;
int T;
int l,m;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&n,&M,&L);
for(i=1;i<=n;i++)
scanf("%ld%ld",&c[i],&w[i]);
for(l=0;l<=L;l++)
for(m=0;m<=M;m++)
if(m==0)dp[l][m]=0;
else dp[l][m]=-inf;
for(i=1;i<=n;i++)
Bi_ZeroOnePack(c[i],w[i]);
if(dp[L][M]<0)dp[L][M]=0;/*表示不能看完所有的电影,也就是不能精确满足M的个数*/
printf("%ld\n",dp[L][M]);
}
return 0;
}