UVA - 711
题目介绍:
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.
大意:
多重背包,判断能否装满总价值一半。先二进制拆分物品的价值,接着01背包,得出结论。
AC代码:
#include<iostream>
#include<cstring>
using namespace std;
int num[6];
const int w[]={1,2,3,4,5,6};
int ss[100000],pos;
int jud[100000];
int main(){
int Case=1;
while(1){
int sum=0;
for(int i=0;i<6;i++){
scanf("%d",&num[i]);
sum+=(num[i]*w[i]);
}
if(!sum)break;
printf("Collection #%d:\n",Case++);
if(sum%2)printf("Can't be divided.");
else{
pos=0;
for(int i=0;i<6;i++){
int k=1,pp=num[i];
while(k<pp){
ss[pos++]=k*w[i];
pp-=k;
k<<=1;
}
if(pp)ss[pos++]=pp*w[i];
}
sum/=2;
memset(jud,0,sizeof(jud));
jud[0]=1;
for(int i=0;i<pos;i++)
for(int j=sum;j>=ss[i];j--)
if(jud[j-ss[i]])
jud[j]=1;
if(!jud[sum])printf("Can't be divided.");
else printf("Can be divided.");
}
cout<<"\n\n";
}
return 0;
}