题目链接:http://www.tzcoder.cn/acmhome/problemdetail.do?method=showdetail&id=1315
描述
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.
输入
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.
输出
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.
思路:
题意大致为有权值为1~6的6中珠子给定每种的个数,问是否能分成权值相同的两份。一开始想错地方了,想要如何分成两堆相同的。后来一想只要分成两份,那如果能分成一堆权值和为所有珠子权值和的一半,那剩下的也是一半……
求可行性直接上背包。(不过要二进制优化下)
#include<bits/stdc++.h>
using namespace std;
const int Ms=5e5+5;
bool dp[Ms];
int main()
{
int a[7],no=1;
while(1)
{
int sum=0,k=0;
for(int i=1;i<=6;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
k+=i*a[i];
}
if(sum==0)break;
int f=0;
if(k&1)f=1;
if(!f)
{
k>>=1;
memset(dp,0,k+1);
dp[0]=1;
for(int i=1;i<=6;i++)
{
for(int j=1;j<=a[i]&&j*i<=k;j<<=1)
{
for(int w=k;w>=j*i;w--)
{
dp[w]|=dp[w-j*i];
}
if(dp[k])break;
}
if(dp[k])break;
}
if(!dp[k])f=1;
}
printf("Collection #%d:\n",no++);
if(f)printf("Can't be divided.\n\n");
else printf("Can be divided.\n\n");
}
return 0;
}
若有什么错误,欢迎指正^ _ ^ 。