1. 程式人生 > >【洛谷】【動態規劃/01背包】P2925 [USACO08DEC]幹草出售Hay For Sale

【洛谷】【動態規劃/01背包】P2925 [USACO08DEC]幹草出售Hay For Sale

ase GC def 算法分析 name ios source sep gis

【題目描述:】

約翰遭受了重大的損失:蟑螂吃掉了他所有的幹草,留下一群饑餓的牛.他乘著容量為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]); }

【洛谷】【動態規劃/01背包】P2925 [USACO08DEC]幹草出售Hay For Sale