1606: [Usaco2008 Dec]Hay For Sale 购买干草
Time Limit: 5 Sec Memory Limit: 64 MB
Submit: 1326 Solved: 980
[Submit][Status][Discuss]
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.
Source
Silver
水题()然而咱还是找了题解才能秒掉
一道背包可行性问题 思路是对于每一个dp[x]=1,都有dp[x+v[i]]=1
最后暴力判断每一个dp[i]是否合法即可
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#define N 100001
using namespace std;
inline int read()
{
int f=1,x=0;char ch=getchar();
while(ch>'9'|ch<'0')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch<='9'&&ch>='0')
{
x=(x<<3)+(x<<1)+ch-'0';
ch=getchar();
}
return f*x;
}
int main()
{
int c=read(),h=read(),j,i,b[100001],v[100001];
b[0]=1;
for(i=1;i<=h;i++)
{
v[i]=read();
for(j=c-v[i];j>=0;j--)
if(b[j]) b[j+v[i]]=1;
}
int ans;
for(i=0;i<=c;i++)
if(b[i])ans=i;
cout<<ans;
}