POJ 1014 Dividing
Dividing
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 66032 Accepted: 17182
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,2,3,4,5,6的6种物品,输入6个数字,数字i代表价值为i的物品有ni个。问能否将物品分成等价的两份(物品当然不能拆开喽)。
输入:
每一行有六个数 分别代表价值为1,2,3,4,5,6的物品的个数,最大物品总数为20000.输入的结束标志为六个0.
输出:
对于第k个样例,输出“Collection #k:”,可以分成等价的两份则输出“Can be divided.”,不可以就输出“Can’t be divided.”。在每个样例后要记得要输出回车。
思路:
0/1背包的二进制优化。。
设一个变量all代表所有物品的价值和。如果all%2==1 则无论怎么分都不可能分成相等的两份。
如果在背包进行的过程中出现了dp[j]==all/2的情况,就可以被分成两份。(如果说的不清楚详情请见代码)。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[100],cases=0,dp[666666],f[666666],tot,all,w;
bool flag;
int main()
{
while(1)
{
cases++;
tot=0;flag=false;all=0;
memset(dp,0,sizeof(dp));
memset(f,0,sizeof(f));
for(int i=1;i<=6;i++) {scanf("%d",&a[i]);all+=a[i]*i;}
if(a[1]||a[2]||a[3]||a[4]||a[5]||a[6])
{
for(int i=1;i<=6;i++)
{
int t=1;
while(a[i]>=t)
{
tot++;
a[i]=a[i]-t;
f[tot]=t*i;
t*=2;
}
tot++;
f[tot]=a[i]*i;
}
if(all%2==1)goto end;
else w=all/2;
for(int i=1;i<=tot;i++)
{
for(int j=all;j>=f[i];j--)
{
dp[j]=max(dp[j],dp[j-f[i]]+f[i]);
if(dp[j]==w)flag=true;
}
}
if(!flag) end: printf("Collection #%d:\nCan't be divided.\n\n",cases);
else printf("Collection #%d:\nCan be divided.\n\n",cases);
}
else break;
}
}