1014Dividing

多重背包问题

#include<iostream>
#include<string.h>
#define maxn 420000+5
using namespace std;
int dp[maxn];
int w[100];
int main(){
    int t=0;
    while(1){
        t++;
        int a[10];
        int m=0;
        for(int i=1;i<=6;i++){
            cin>>a[i];
            m=m+i*a[i];
        }
        if (m%2!=0) {
            cout<<"Collection #"<<t<<":"<<endl;
            cout<<"Can't be divided."<<endl;
            cout<<endl;
            continue;
        }else
        {
        m=m/2;
        if(a[2]+a[1]+a[3]+a[4]+a[5]+a[6]==0) break;
        int total=6;
        for(int i=1;i<=6;i++){
            int s=1;
            while(a[i]>s){
                total++;
                w[total]=i*s; 
                a[i]=a[i]-s;
                s=s*2;
            }
            w[i]=a[i]*i;
        }//现在已经转化成01背包    
        memset(dp,0,sizeof(dp));
        dp[0]=1;
        for(int i=1;i<=total;i++){
            for(int j=m;j>=w[i];j--){
                if (dp[j-w[i]])
                    dp[j]=1;
            }
        }
        if(!dp[m]) {
            cout<<"Collection #"<<t<<":"<<endl;
            cout<<"Can't be divided."<<endl;
            cout<<endl;
        }else{
            cout<<"Collection #"<<t<<":"<<endl;
            cout<<"Can be divided."<<endl;
            cout<<endl;
        }
    }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dowson/p/3258429.html