标签:ast ural amp where imu ++ ems mon bsp
InputEach 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.
OutputFor 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,2,3,4,5,6硬币的对应数量,判断能否将硬币组合为总价值的一半,比如:输入1 1 1 1 1 1,说明价值为1,2,3,4,5,6的硬币的数量都同为1,总价值为21,我们组合出得一半是10价值的硬币,另一半是11,所以不能够均分。
思路:注意最多的数量范围是20000,dp数组最大为120000,所以这道题明显是多重背包。我们将总价值ans计算好以后,除以2作为背包的容量v,dp数组存储v容量下的最大价值,最后判断dp[v]是否等于ans-v即可,不能够直接用dp[v]是否等于v判断,原因参见我给出的题意上的样例
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; #define N 120010 int dp[N],v,ans,num[10]; int value[7] = {0,1,2,3,4,5,6}; void CompletePack(int v,int value) { int i; for(i = value; i <= v; i ++) dp[i] = max(dp[i],dp[i-value]+value); return; } void ZeroOnePack(int cost,int value) { int i; for(i = v; i >= cost; i --) dp[i] = max(dp[i],dp[i-cost]+value); return; } int main() { int i,j,k,x; 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])) { ans = 0; memset(dp,0,sizeof(dp)); for(i = 1; i <= 6; i ++) ans += num[i]*value[i]; v= ans/2; for(i = 1; i <= 6; i ++) { if(num[i]*value[i] > v) CompletePack(v,value[i]); else { k = 1; while(num[i]>0) { x = min(k,num[i]); ZeroOnePack(x*value[i],x*value[i]); num[i]-=x; k*=2; } } } printf("Collection #%d:\n",++t); if(dp[v] == ans-v) printf("Can be divided.\n\n"); else printf("Can‘t be divided.\n\n"); } return 0; }
【背包专题】G - Dividing hdu 1059【多重背包】
标签:ast ural amp where imu ++ ems mon bsp
原文地址:http://www.cnblogs.com/chengdongni/p/7435428.html