hdoj 1014 Divding(03背包问题)

来源:互联网 发布:七天网络网页版 编辑:程序博客网 时间:2024/06/05 16:43

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 01 0 0 0 1 10 0 0 0 0 0
 

Sample Output
Collection #1:Can't be divided.Collection #2:Can be divided.

题意:

给出6种物品价值分别1~6,每种物品都有一定的数量

问能不能将这些物品分成两半 两半的价值相等


别人的思路:

是一个多重背包问题,相当于背包称重固定,物品件数有限,把物品将背包刚好塞满。

数据较大 用bool的类型来写

起点为s/2(s为总价值), 若s为奇数则不能分成两半

dp[i]=1  表示可以将物品凑成价值i,若dp[s/2]则可以分成两半。

我一开始是把他转化为一个序列 求其中子序列相加和等于S/2

后来这个方法更好   以后遇到这种题可以转化成这个方式来写


代码如下:

#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>using namespace std;#define N 80011int a[7],dp[N];int main(){int i,j,k,n,m,t=1;while(scanf("%d %d %d %d %d %d",&a[1],&a[2],&a[3],&a[4],&a[5],&a[6])!=EOF){if(a[1]==0&&a[2]==0&&a[3]==0&&a[4]==0&&a[5]==0&&a[6]==0) break;int s=0;j=0,m=0;for(i=1;i<=6;i++)  s+=a[i]*i;      printf("Collection #%d:\n",t++);          if(s%2){printf("Can't be divided.\n\n");  continue;    }    k=0;   s/=2;   memset(dp,0,sizeof(dp));   dp[0]=1; for(i=1;i<=6;i++)  { if(a[i]==0) continue; for(k=1;k<=a[i];k*=2) { for(j=s;j>=0;j--) { if(dp[j]==0||j+i*k>s) continue; dp[j+i*k]=1;}a[i]-=k;}if(a[i]>0){for(j=s;j>=0;j--){if(dp[j]==0||j+i*a[i]>s)continue;dp[j+i*a[i]]=1;}} } if(dp[s]==1)                  printf("Can be divided.\n");              else printf("Can't be divided.\n");   printf("\n"); }return 0; }


1 0
原创粉丝点击