多重背包问题:POJ2392

这是一道完全背包问题,只不过增加了限制条件。

在更新最大值的时候,我注释掉了错误的方式,却不明白为什么是错误的,如果有人看到这篇博客,并且知道为什么那样更新是错误的,请指教,谢谢。

上代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
#define MAXV 410
#define MAXM 40010

typedef struct{int h,a,c;}block;

block s[MAXV];
int cmp(block x,block y){return x.a<y.a;}

int dp[MAXM];
int use[MAXM];
int main()
{
    int i,j,k,max,maxn=0,max1=0;
    while(scanf("%d",&k)!=EOF){
        for(i=1;i<=k;i++)
        {
            scanf("%d %d %d",&s[i].h,&s[i].a,&s[i].c);
            if(maxn<s[i].a){maxn = s[i].a;}
        }
        sort(s+1,s+1+k,cmp);
        memset(dp,0,sizeof(dp));
        dp[0] = 1;
        max=0;
        for(i=1;i<=k;i++){
            memset(use,0,sizeof(use));
            for(j=s[i].h;j<=s[i].a;j++){
                if(dp[j-s[i].h]&&
                    dp[j]<dp[j-s[i].h]+s[i].h&&
                    dp[j-s[i].h]+s[i].h-1<=s[i].a&&
                    use[j-s[i].h]<s[i].c)
                {
                    dp[j] = dp[j-s[i].h]+s[i].h;
                    use[j] = use[j-s[i].h]+1;
                    //if(dp[j]>max){max = dp[j];}//按照这种方式更新最大值却出现错误?为何?        
                }            
            }
        }

        for(i=0;i<=maxn;i++){if(max<dp[i]){max = dp[i];}}//i最大不会超过maxn
        printf("%d
",max-1);
    }    
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/yueyanglou/p/5354205.html