动态规划-多重背包问题

 

 

// 朴素解法
#include <iostream>
using namespace std;

const int N = 110;

int n, m;
int s[N], v[N], w[N];
int f[N][N];

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; ++ i)   cin >> v[i] >> w[i] >> s[i];
    
    for (int i = 1; i <= n; ++ i)
        for (int j = 0; j <= m; ++ j)
            for (int k = 0; k <= s[i] && k * v[i] <= j; ++ k)
                f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i]);
                
    cout << f[n][m] << endl;
    
    return 0;
}
// 二进制优化
#include <iostream>
using namespace std;

const int N = 25000, M = 2010;

int v[N], w[N], f[M];
int n, m;

int main()
{
    cin >> n >> m;
    
    int cnt = 0;
    for (int i = 1; i <= n; ++ i)
    {
        int a, b, s;
        cin >> a >> b >> s;
        
        int k = 1;
        while (k <= s)
        {
            cnt ++;
            v[cnt] = k * a;
            w[cnt] = k * b;
            s = s - k;
            k = k * 2;
        }
        
        if (s > 0)
        {
            cnt ++;
            v[cnt] = s * a;
            w[cnt] = s * b;
        }
    }
    
    n = cnt;
    
    for (int i = 1; i <= n; ++ i)
        for (int j = m; j >= v[i]; -- j)
            f[j] =  max(f[j], f[j - v[i]] + w[i]);
            
    cout << f[m] << endl;
    
    return 0;
}

 

posted @ 2021-08-29 17:20  青衫客36  阅读(31)  评论(0编辑  收藏  举报