1028: Dividing Up
| Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
|---|---|---|---|---|---|
| 10s | 8192K | 2055 | 420 | Standard |
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 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.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int f[20005*6],a[10],w[10],num[10];
int main()
{
int n=6,m;
for(int i=0;i<n;i++) a[i]=i+1,w[i]=i+1;
int pl=1;
while(1)
{
int sum=0;
for(int i=0;i<n;i++) {scanf("%d",&num[i]);sum+=a[i]*num[i];}
if(sum==0) break;
memset(f,0,sizeof(f));
printf("Collection #%d:/n",pl++);
if(sum&1)
{
printf("Can't be divided./n/n");
continue;
}
int m=sum/2;
for(int i=0;i<n;i++)
{
if(a[i]*num[i]>m)
{
for(int j=a[i];j<=m;j++) f[j]=max(f[j],f[j-a[i]]+w[i]);
}
else
{
int l=num[i],k=1;
while(k<l)
{
for(int j=m;j>=k*a[i];j--) f[j]=max(f[j],f[j-k*a[i]]+k*w[i]);
l-=k;
k*=2;
}
for(int j=m;j>=l*a[i];j--) f[j]=max(f[j],f[j-l*a[i]]+l*w[i]);
}
}
if(f[m]==m) printf("Can be divided./n/n");
else printf("Can't be divided./n/n");
}
return 0;
}
本文介绍了一道经典的计算机编程问题——如何公平地将不同价值的物品(如大理石)分成两份,每份总价值相等。该问题涉及动态规划算法,通过实例输入输出展示了问题的解决过程。
5万+

被折叠的 条评论
为什么被折叠?



