【洛谷】【动态规划/01背包】P2925 [USACO08DEC]干草出售Hay For Sale

【题目描述:】

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

他最多可以运回多少体积的干草呢?

【输入格式:】

  • Line 1: Two space-separated integers: C and H

  • Lines 2..H+1: Each line describes the volume of a single bale: V_i

【输出格式:】

  • Line 1: A single integer which is the greatest volume of hay FJ can purchase given the list of bales for sale and constraints.

    [算法分析:]

一看就是01背包,但是交上板子以后TLE了,加了炒鸡快读才刚好1000ms卡过

于是考虑优化算法:

类似于搜索的剪枝,对f[j]进行处理的时候,如果f[j]=c(最大容量)了,那输出c直接结束程序。

  • 优化前:1000ms

  • 优化后:108ms

    [Code:]

#include<iostream>
#include<cstdio>
#define re register
using namespace std;

const int MAXN = 5000 + 1;
const int MAXC = 50000 + 1;

int n, c, v[MAXN];
int f[MAXC];

inline char gc()
{
    static char buff[1000000],*S=buff,*T=buff;
    return S==T&&(T=(S=buff)+fread(buff,1,1000000,stdin),S==T)?EOF:*S++;
}

inline int read() {
    int x = 0; char ch = gc();
    while(!isdigit(ch)) ch = gc();
    while(isdigit(ch))
        x = (x << 3) + (x << 1) + ch - 48, ch = gc();
    return x;
}

int main() {
    c = read(), n = read();
    for(re int i=1; i<=n; ++i)
        v[i] = read();
    for(re int i=1; i<=n; ++i)
        for(re int j=c; j>=v[i]; --j) {
            f[j] = max(f[j], f[j-v[i]]+v[i]);
            if(f[j] == c) {
                printf("%d", c);
                return 0;
            }
        }
    printf("%d", f[c]);
}

转载于:https://www.cnblogs.com/devilk-sjj/p/9210829.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值