您的位置:首页 > 其它

POJ 1014 Dividing(多重背包)

2015-03-14 15:12 295 查看
Dividing

Description

MarshaandBillownacollectionofmarbles.Theywanttosplitthecollectionamongthemselvessothatbothreceiveanequalshareofthemarbles.Thiswouldbeeasyifallthemarbleshadthesamevalue,becausethentheycouldjustsplitthecollectioninhalf.Butunfortunately,someofthemarblesarelarger,ormorebeautifulthanothers.So,MarshaandBillstartbyassigningavalue,anaturalnumberbetweenoneandsix,toeachmarble.Nowtheywanttodividethemarblessothateachofthemgetsthesametotalvalue.Unfortunately,theyrealizethatitmightbeimpossibletodividethemarblesinthisway(evenifthetotalvalueofallmarblesiseven).Forexample,ifthereareonemarbleofvalue1,oneofvalue3andtwoofvalue4,thentheycannotbesplitintosetsofequalvalue.So,theyaskyoutowriteaprogramthatcheckswhetherthereisafairpartitionofthemarbles.
Input

Eachlineintheinputfiledescribesonecollectionofmarblestobedivided.Thelinescontainsixnon-negativeintegersn1,...,n6,whereniisthenumberofmarblesofvaluei.So,theexamplefromabovewouldbedescribedbytheinput-line"101200".Themaximumtotalnumberofmarbleswillbe20000.
Thelastlineoftheinputfilewillbe"000000";donotprocessthisline.
Output

For
eachcollection,output"Collection#k:",wherekisthenumberofthe
testcase,andtheneither"Canbedivided."or"Can'tbedivided.".

Outputablanklineaftereachtestcase.
SampleInput

101200
100011
000000

SampleOutput

Collection#1:
Can'tbedivided.

Collection#2:
Canbedivided.

这道题目多重背包入手真心很简单,题目要求,将弹珠根据价值的大小均分给两个人。
多重背包的模板题目里,问题的相关条件有:背包的体积、物品的种类、每种物品的数量、每种物品所占的体积。这是通常情况,而这道题目里,只有

物品的种类、每种物品的数量、每种物品所占的体积这3个条件,但是题目也要求简单,就是看这堆弹珠是否能够均分,所以,背包的体积你可以当作是题目极限条件那么大。
然后运用二进制的思想写出多重背包就好.其实我也就是昨天才学会了多重背包。


#include<cstring>
#include<cstdio>
#include<algorithm>
#include<iostream>

usingnamespacestd;
constintmax_size=20000*6+10;
intmain()
{
intval[10];//val数组里存放每种弹珠的数量
intdp[max_size];//dp数组开题目极限那么大

intcas=1;

while(cas)
{
inttag=0;
for(inti=0;i<6;i++)
{
scanf("%d",val+i);
if(val[i]==0)
{
tag++;
}
}
memset(dp,0,sizeof(dp));
if(tag==6)
break;
else
{
inttot=0;
for(inti=0;i<6;i++)
{
tot+=val[i]*(i+1);
}
inthalf=tot/2;
inthalf1=tot-half;
if(half==half1)
{
boolflag=false;
for(inti=0;i<6;i++)
{
intk=1;
while(k<val[i])
{
for(intj=max_size;j-(i+1)*k>=0;j--)
{
dp[j]=max(dp[j],dp[j-(i+1)*k]+(i+1)*k);
if(dp[j]==half)//在dp过程中,找寻是否有一种状态,满足将弹珠平分这一条件
{
flag=true;
break;
}
}
val[i]-=k;
k*=2;
if(flag==true)
break;
}
if(flag!=true)
{
for(intj=max_size;j-val[i]*(i+1)>=0;j--)
{
dp[j]=max(dp[j],dp[j-(i+1)*val[i]]+(i+1)*val[i]);
if(dp[j]==half)
{
flag=true;
break;
}
}
}
else
{
printf("Collection#%d:\n",cas);
printf("Canbedivided.\n");
break;
}
}
if(flag!=true)
{
printf("Collection#%d:\n",cas);
printf("Can'tbedivided.\n");
}
}
else
{
printf("Collection#%d:\n",cas);
printf("Can'tbedivided.\n");
}
}
cas++;
printf("\n");//GG,我去,因为没看要多输出一行空行,PE一次
}

return0;
}


ViewCode



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: