hdu1059(多重背包)

链接:点击打开链接

题意:给出价值为1~6的硬币的金额,问是否正好能够取出总价值一半的硬币

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int a[10],used[200005],f[200005];
int main(){
    int i,j,cas,sum,sign;
    cas=1;
    while(scanf("%d%d%d%d%d%d",&a[0],&a[1],&a[2],&a[3],&a[4],&a[5])!=EOF&&(a[0]||a[1]||a[2]||a[3]||a[4]||a[5])){
        sum=sign=0;
        for(i=0;i<6;i++)
        sum+=(i+1)*a[i];
        if(sum%2){                              //奇数直接输出
            printf("Collection #%d:\nCan't be divided.\n\n",cas++);
            continue;
        }
        memset(f,0,sizeof(f));
        f[0]=1;
        for(i=0;i<6;i++){                       //多重背包
            memset(used,0,sizeof(used));
            for(j=i+1;j<=sum;j++){
                if(!f[j]&&f[j-(i+1)]&&used[j-(i+1)]<a[i]){
                    f[j]=1;
                    used[j]=used[j-(i+1)]+1;
                    if(j==sum/2){               //满足时即跳出
                        sign=1;
                        goto next;
                    }
                }
            }
        }
        next:
        if(sign)
        printf("Collection #%d:\nCan be divided.\n\n",cas++);
        else
        printf("Collection #%d:\nCan't be divided.\n\n",cas++);
    }
    return 0;
}


 

你可能感兴趣的:(源码,动态规划,ACM)