0-1背包、完全背包及多重背包的应用

http://acm.hdu.edu.cn/showproblem.php?pid=3732

Sample Input
5 20 go 5 8 think 3 7 big 7 4 read 2 6 write 3 5
 

Sample Output
15

 

☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆

 

#include <iostream>
#include <cstdio>
using namespace std;

const
int W = 11;
const
int V = 11;
const
int M = 10010;
int
goods[W][V],dp[M],cap,n;

void
zeroOnePack(int weight, int value){
    for
(int i=cap;i>=weight;i--)

        dp[i]=max(dp[i],dp[i-weight]+value);
}


void
completePack(int weight, int value){
    for
(int i=weight;i<=cap;i++){

        dp[i]=max(dp[i],dp[i-weight]+value);
    }
}


void
multiPack(int weight, int value, int num){
    if
(weight*num>=cap){

        completePack(weight,value);
    }

    else
{
        int
k=1;
        while
(k<num){

            zeroOnePack(weight*k,value*k);
            num-=k;
            k*=2;
        }

        zeroOnePack(weight*num,value*num);
    }
}



int
main(){
    int
i,j,weight,value;
    while
(scanf("%d%d",&n,&cap)!=EOF){

        memset(goods,0,sizeof goods);
        memset(dp,0,sizeof dp);
        for
(i=0;i<n;i++){

            scanf("%*s%d%d",&value,&weight);
            goods[weight][value]++;
        }

        for
(i=0;i<W;i++){
            for
(j=0;j<V;j++){
                if
(goods[i][j]){

                    multiPack(i,j,goods[i][j]);
                }
            }
        }

        printf("%d\n",dp[cap]);
    }
   
    return
0;
}

posted @ 2011-05-05 18:43  Pengchao Bai  阅读(190)  评论(0)    收藏  举报