[Usaco2008 Dec]Hay For Sale 购买干草[01背包水题]
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.
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
题解:
很水的01背包模板题;
把01背包中的v[i]改为w[i]即可;
这里由于空间限制只能用一维的数组;
附上代码:
#include <iostream> #include <cstdio> #include <cstring> #include <string> using namespace std; int n,c,m; int a[5001]; int f[50001]; int main(){ freopen("hay4sale.in","r",stdin);freopen("hay4sale.out","w",stdout); scanf("%d%d",&m,&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); } for(int i=1;i<=n;i++){ for(int j=m;j>=0;j--){ if(a[i]<=j) f[j]=max(f[j],f[j-a[i]]+a[i]); } } cout<<f[m]; return 0; }