Problem Description
Marsha and Bill own a collection of marbles. They want to split the collection among themselves so that both receive an equal share of the marbles. This would be easy if all the marbles had the same value, because then they could just split the collection in half. But unfortunately, some of the marbles are larger, or more beautiful than others. So, Marsha and Bill start by assigning a value, a natural number between one and six, to each marble. Now they want to divide the marbles so that each of them gets the same total value.
Unfortunately, they realize that it might be impossible to divide the marbles in this way (even if the total value of all marbles is even). For example, if there are one marble of value 1, one of value 3 and two of value 4, then they cannot be split into sets of equal value. So, they ask you to write a program that checks whether there is a fair partition of the marbles.
Input
Each line in the input describes one collection of marbles to be divided. The lines consist of six non-negative integers n1, n2, ..., n6, where ni is the number of marbles of value i. So, the example from above would be described by the input-line ``1 0 1 2 0 0''. The maximum total number of marbles will be 20000.
The last line of the input file will be ``0 0 0 0 0 0''; do not process this line.
Output
For each colletcion, output ``Collection #k:'', where k is the number of the test case, and then either ``Can be divided.'' or ``Can't be divided.''.
Output a blank line after each test case.
Sample Input
1 0 1 2 0 0
1 0 0 0 1 1
0 0 0 0 0 0
Sample Output
Collection #1:
Can't be divided.
Collection #2:
Can be divided.
好难,我自闭了。
题意:玻璃球价值从1-6数量给你,问你能不能均分成等价的两份。
思路:多重背包二进制优化模板。背包容量是总价的一半,看看能不能装满。数据很大,要用二进制优化转01背包。下面代码详解。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 6 int dp[120005],a[10]; 7 int m; 8 9 void completepack(int c,int w){//正向完全背包 10 for(int i=c;i<=m;i++){ 11 if(dp[i-c]+w>dp[i]) dp[i]=dp[i-c]+w; 12 } 13 } 14 void zeroonepack(int c,int w){//逆向01背包 15 for(int i=m;i>=c;i--){ 16 if(dp[i-c]+w>dp[i]) dp[i]=dp[i-c]+w; 17 } 18 } 19 //这样1,2,4,8的塞肯定能覆盖所有塞的数量。 20 void multiplepack(int c,int w,int t){//c价值、w重量、t该种数量 21 if(t*w>=m) completepack(c,w);//如果t*w该种总重大于容量 22 else{//类似于快速幂的操作 23 int k=1; 24 while(k<t){//如果小于该种剩余 25 zeroonepack(c*k,w*k);//假设新物品(k(1,2,4,8...)个该种物品拼成) 26 t-=k;//更新该种剩余 27 k<<=1;//k*=2 28 } 29 zeroonepack(c*t,w*t);//剩余的合成一个新物品 30 } 31 } 32 33 int main(){ 34 int cnt=0; 35 while(1){ 36 m=0; 37 for(int i=1;i<=6;i++){ 38 scanf("%d",&a[i]); 39 m+=a[i]*i; 40 } 41 if(m==0) break; 42 printf("Collection #%d: ",++cnt); 43 44 if(m&1){//m是奇数肯定不能均分 45 printf("Can't be divided. "); 46 continue; 47 } 48 m>>=1;//m取总量的一半 49 memset(dp,0,sizeof(dp)); 50 for(int i=1;i<=6;i++) 51 multiplepack(i,i,a[i]);//重量和价值一样 52 53 if(dp[m]==m) printf("Can be divided. "); 54 else printf("Can't be divided. "); 55 56 } 57 return 0; 58 }