您的位置:首页 > 其它

poj3628 Bookshelf 2(0/背包)

2012-09-23 11:07 274 查看
题意:就是给出n和b,然后给出n个数,用这n个数中的某些,求出一个和,这个和是>=b的最小值,输出最小值与b的差。

分析:这道题很简单,是很明显的01背包问题,这里的n个物品,每个物品的重量为c[i],价值为w[i]并且c[i]==w[i],,容量为所有c[i]的和sum。只要在f[]中从头开始找,找到一个最小>=b的就是题目要的解



Description

FarmerJohnrecentlyboughtanotherbookshelfforthecowlibrary,buttheshelfisgettingfilledupquitequickly,andnowtheonlyavailablespaceisatthetop.

FJhasNcows(1≤
N≤20)eachwithsomeheightofHi(1≤Hi≤1,000,000-theseareverytallcows).Thebookshelfhasaheightof
B(1≤B≤S,whereSisthesumoftheheightsofallcows).

Toreachthetopofthebookshelf,oneormoreofthecowscanstandontopofeachotherinastack,sothattheirtotalheightisthesumofeachoftheirindividualheights.Thistotalheightmust
benolessthantheheightofthebookshelfinorderforthecowstoreachthetop.

Sinceatallerstackofcowsthannecessarycanbedangerous,yourjobistofindthesetofcowsthatproducesastackofthesmallestheightpossiblesuchthatthestackcanreachthebookshelf.
Yourprogramshouldprinttheminimal'excess'heightbetweentheoptimalstackofcowsandthebookshelf.

Input

*Line1:Twospace-separatedintegers:
NandB

*Lines2..N+1:Linei+1containsasingleinteger:Hi

Output

*Line1:Asingleintegerrepresentingthe(non-negative)differencebetweenthetotalheightoftheoptimalsetofcowsandtheheightoftheshelf.

SampleInput
516
3
1
3
5
6


SampleOutput
1


代码:

#include<iostream>
usingnamespacestd;
intf[1000050],c[10000];
intmain()
{
inti,j,n,v,sum;
while(scanf("%d%d",&n,&v)!=EOF)
{
memset(f,0,sizeof(f));
memset(c,0,sizeof(c));
sum=0;
for(i=1;i<=n;i++)
{
scanf("%d",&c[i]);
sum+=c[i];
}
for(i=1;i<=n;i++)
{
for(j=sum;j>=c[i];j--)
f[j]=max(f[j],f[j-c[i]]+c[i]);
}
for(i=1;i<=sum;i++)
{
if(f[i]>=v)
{
printf("%d\n",f[i]-v);
break;
}
}
}
return0;
}

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