poj 1014 Dividing

//poj 1014 Dividing 也有人用搜索做,本人觉得是比较基础的背包题,不过要加二进制的优化。
#include <iostream>
#include <algorithm>

using namespace std;

int a[7];
int b[10000];
int dp[60000];


int main()
{
    for (int tm=1;;++tm)
    {
       
        int sum=0;
        bool flag=true;
        for (int i=1;i<=6;i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i]*i;
            if (a[i]%2) flag=false;
        }
        if (sum==0) break;
        printf("Collection #%d:/n",tm);
        if (flag) printf("Can be divided./n/n");
        else if (sum%2) printf("Can't be divided./n/n");
        else
        {
            sum/=2;
            int m=0;
            for (int i=1;i<=6;i++)
            {
                int k=1;
                while(a[i]>=k)
                {
                           a[i]-=k;
                           b[m++]=k*i;
                           k<<=1;
                }
                if (a[i]) b[m++]=a[i]*i;
            }
            memset(dp,0,sizeof(dp));
            dp[0]=1;
           for (int i=0;i<m;i++)
            {
                if (sum-b[i]>=0 && dp[sum-b[i]]) { dp[sum]=1; break;}
                for (int k=sum-1;k>=b[i];k--) if (dp[k-b[i]]) dp[k]=1;
            }
           
            if (dp[sum]) printf("Can be divided./n/n");
            else printf("Can't be divided./n/n");
        }
    }
   // system("pause");
    return 0;
}

 

你可能感兴趣的:(poj 1014 Dividing)