poj 1014 多重背包压缩为01

#include<stdio.h>
#include<string.h>
int dp[250000];
int f[250];
int max(int a,int b){
   return a>b?a:b;

}
int main(){
    int n[10];
    int index=0;
    int t;
     while(1){
         memset(dp,-1000000,sizeof(dp));
         memset(f,0,sizeof(f));
         dp[0]=0;
         int sum=0;
         for(int i=1;i<=6;i++){
             scanf("%d",&n[i]);
                sum+=n[i]*i;
         }
         if(sum==0)
            return 0;
         if(sum%2!=0){
           printf("Collection #%d:\nCan't be divided.\n\n", ++index);
           continue;
         }
         int k=1;
           for(int i=1;i<=6;i++)
        {
            if(n[i]==0)
             continue;
            t=1;
            while(n[i]-t>0)//二进制压缩为一般01背包
            {
                f[k++]=t*i;
                n[i]-=t;
                t*=2;
            }
            f[k++]=n[i]*i;
        }
         for(int i=1;i<=k;i++){
           for(int j=sum/2;j>=f[i];j--)

                dp[j]=max(dp[j],dp[j-f[i]]+f[i]);

         }

         if(dp[sum/2]<0)
              printf("Collection #%d:\nCan't be divided.\n\n", ++index);
         else
             printf("Collection #%d:\nCan be divided.\n\n", ++index);





}
return 0;
}

你可能感兴趣的:(背包)