HDOJ(HDU).1059 Dividing(DP 多重背包+二进制优化)

2/22/2017来源:ASP.NET技巧人气:862

HDOJ(HDU).1059 Dividing(DP 多重背包+二进制优化)

题意分析

给出一系列的石头的数量,然后问石头能否被平分成为价值相等的2份。首先可以确定的是如果石头的价值总和为奇数的话,那么肯定不能被平分。若为偶数,则对valuesum/2为背包容量,全体石头为商品做完全背包。把完全背包进行二进制优化后,转为01背包即可。

代码总览

#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define nmax 20005 * 6 #define INIT(x,y) memset(x,y,sizeof(x)) using namespace std; int c[6]; int val[150],num[150]; int dp[nmax]; int main() { //freopen("in.txt","r",stdin); int cas = 0; while(1){ INIT(val,0);INIT(num,0);INIT(c,0); int judge = false; int sum = 0; for(int i = 0; i<6;++i) {scanf("%d",&c[i]); sum+=c[i] * (i+1);} if(sum == 0) break; PRintf("Collection #%d:\n",++cas); int cnt = 0; if(sum %2 == 0){ for(int i = 0 ;i<6;++i){ for(int j =1; j<=c[i]; j<<=1){ val[cnt] = j*(i+1); num[cnt++] = j; c[i]-=j; } if(c[i]>0){ val[cnt] = c[i] * (i+1); num[cnt++] = c[i]; } } INIT(dp,0); dp[0] = 1; for(int i = 0; i<=cnt ;++i){ for(int j = sum; j>=val[i];--j) if(dp[j-val[i]]) dp[j] = 1; } if(dp[sum/2] == 1) judge = true; } if(judge) printf("Can be divided.\n\n"); else printf("Can't be divided.\n\n"); } return 0; }