Title Description
P2925 [USACO08DEC]Hay For Sale S
Solution: 0-1 knapsack problem
Here there is a slight optimization: early when the carriage is filled, the program may end the output
#include <bits/stdc++.h>
using namespace std;
int main()
{
int c, h;
scanf("%d%d", &c, &h);
int v[h+1], dp[c+1];
for(int i=1;i<=h;i++)
{
scanf("%d", v+i);
}
memset(dp, 0, sizeof(dp));
for(int i=1;i<=h;i++)
{
for(int j=c;j>=v[i];j--)
{
dp[j] = max(dp[j], dp[j-v[i]]+v[i]);
if(dp[c]==c)
{
printf("%d", c);
return 0;
}
}
}
printf("%d", dp[c]);
return 0;
}