洛谷 P2925 - Hay For Sale S

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;
}
Published 152 original articles · won praise 22 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_38204302/article/details/105199541