Dividing
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 file describes one collection of marbles to be divided. The lines contain six non-negative integers n1 , . . . , 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 collection, 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价值的东西(具体单词我没有去查),输入6个数,分别代表1~6价值对应东西的数量,输入6个0时结束输入,每个样例后单独输出一行。判断输入的物品总价值能否平均分,比如第二个样例,价值为1的物品有1个,价值为5的物品有1个,价值为6的物品有1个,而1+5 == 6,所以可以均分。
思路:现将总价值对半分为sum2,背包容量就是sum2,找到最大价值dp[sum2],比较是否等于另一半价值sum-sum2
#include#include int w[7] = {0,1,2,3,4,5,6};int num[7];int dp[200000];int sum2;int max(int a,int b){ if(a > b) return a; return b;}void CompletePack(int cost,int V){ int i; for(i = cost; i <= V; i ++) dp[i] = max(dp[i],dp[i-cost]+cost); return ;}void ZeroOnePack(int cost,int V){ int i; for(i = V; i >= cost; i --) dp[i] = max(dp[i],dp[i-cost]+cost); return;}int main(){ int i,j; int sum,k; int t = 0; while(scanf("%d%d%d%d%d%d",&num[1],&num[2],&num[3],&num[4],&num[5],&num[6]),num[1]+num[2]+num[3]+num[4]+num[5]+num[6]!=0) { sum = 0; t++; memset(dp,0,sizeof(dp)); for(i = 1; i <= 6; i ++) sum += (num[i]*w[i]); sum2 = sum/2; for(i = 1; i <= 6; i ++) { if(num[i]*w[i] >= sum2) CompletePack(w[i],sum2); else { k = 1; while(k < num[i]) { ZeroOnePack(k*w[i],sum2); num[i] -= k; k*= 2; } ZeroOnePack(num[i]*w[i],sum2); } } printf("Collection #%d:\n",t); if(dp[sum2] != sum-sum2) printf("Can't be divided.\n\n"); else printf("Can be divided.\n\n"); } return 0;}