BZOJ 1606: [Usaco2008 Dec]Hay For Sale 购买干草【01背包】

1606: [Usaco2008 Dec]Hay For Sale 购买干草

Time Limit: 5 Sec Memory Limit: 64 MB

Description

约翰遭受了重大的损失:蟑螂吃掉了他所有的干草,留下一群饥饿的牛.他乘着容量为C(1≤C≤50000)个单位的马车,去顿因家买一些干草. 顿因有H(1≤H≤5000)包干草,每一包都有它的体积Vi(l≤Vi≤C).约翰只能整包购买,他最多可以运回多少体积的干草呢?

Input

第1行输入C和H,之后H行一行输入一个Vi.

Output

最多的可买干草体积.

Sample Input

7 3 //总体积为7,用3个物品来背包
2
6
5
The wagon holds 7 volumetric units; three bales are offered for sale with
volumes of 2, 6, and 5 units, respectively.

Sample Output

7 //最大可以背出来的体积

HINT

Buying the two smaller bales fills the wagon.

题解

这题典型的背包,但是我们需要加一道优化,边读变更新,那么时间效率会更高。

代码如下

#include<cstdio>
#include<cctype>
#include<algorithm>
using namespace std;
int Alv,Now,n;bool f[50005];
int read(){
    int ret=0;char ch=getchar();bool f=1;
    for(;!isdigit(ch);ch=getchar()) f^=!(ch^'-');
    for(; isdigit(ch);ch=getchar()) ret=(ret<<3)+(ret<<1)+ch-48;
    return f?ret:-ret;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("prob.in","r",stdin);
    freopen("prob.out","w",stdout);
    #endif
    Alv=read();n=read();f[0]=1;
    for(int i=1;i<=n;i++){
        int x=read();Now+=x;
        if(Now>Alv) Now=Alv;
        for(int j=Now;j>=x;j--) f[j]|=f[j-x];
    }
    int Ans=0;
    for(int j=Alv;j;j--) if(f[j]){Ans=j;break;}
    printf("%d\n",Ans);
    return 0;
}
posted @ 2018-05-14 20:41  XSamsara  阅读(152)  评论(0编辑  收藏  举报