计蒜客 蒜头君的购物袋1(DP)

蒜头君的购物袋1

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>

#define maxn 32
#define maxv 20005
using namespace std;

bool dp[maxn][maxv];
int weight[maxn];

int main()
{
    //freopen("data.in","r",stdin);
    ios::sync_with_stdio(false);

    memset(weight,0,sizeof(weight));
    memset(dp, false, sizeof(dp));

    int w;
    int n;
    cin >> w >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> weight[i];
    }

    dp[0][0] = true;
    for(int i = 1; i <= n; ++i) {
        for(int j = 0; j <= w; ++j) {
            dp[i][j] = dp[i-1][j];
            if(j >= weight[i-1] && dp[i-1][j-weight[i-1]]) {
                dp[i][j] = true;
            }
        }
    }

    for(int j = w; j >= 0; --j) {
        if(dp[n][j]) {
            cout << w-j << endl;
            break;
        }
    }

    return 0;
}



猜你喜欢

转载自blog.csdn.net/ccshijtgc/article/details/80893756