【动态规划】【多重背包】[HDU 1059]Dividing

实际上就是统计一下所有的元素一共有多少,如果是一个奇数那么肯定不能被分成两半,如果是一个偶数,那么就开一个总和的一半的背包,然后看背包最大能够装多少,如果可以刚好装满,那么说名肯定可以被分成两半,然后因为数量有限,所以搞一个多重背包,我的代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 100000;
int f[MAXN+10], num[7];
int main(){
    int c, wei, numb, cse=0;
    while(scanf("%d%d%d%d%d%d",&num[1],&num[2],&num[3],&num[4],&num[5],&num[6])!=EOF){
        if(!num[1]&&!num[2]&&!num[3]&&!num[4]&&!num[5]&&!num[6]) break;
        memset(f, 0, sizeof f);
        printf("Collection #%d:\n", ++cse);
        int v = num[1]+2*num[2]+3*num[3]+4*num[4]+5*num[5]+6*num[6];
        if(v % 2 == 1) printf("Can't be divided.\n");
        else{
            v /= 2;
            for(int i=1;i<=6;i++){
                numb = num[i];
                c = wei = i;
                int k=1, end;
                if(numb*c > v)
                    numb = v / c;
                while(k <= numb){
                    end = k*c;
                    for(int V=v;V>=end;V--)
                        f[V] = max(f[V], f[V-k*c]+wei*k);
                    numb -= k;
                    k *= 2;
                }
                if(numb > 0){
                    end = numb*c;
                    for(int V=v;V>=end;V--)
                        f[V] = max(f[V], f[V-numb*c]+wei*numb);
                }
            }
            if(f[v] == v) printf("Can be divided.\n");
            else printf("Can't be divided.\n");
        }
        printf("\n");
    }

    return 0;
}

posted on 2015-06-24 15:00  JeremyGuo  阅读(156)  评论(0编辑  收藏  举报

导航