1. 程式人生 > 其它 >AcWing 5. 多重揹包問題 II

AcWing 5. 多重揹包問題 II

題目連結

https://www.acwing.com/problem/content/5/

題目思路

多重揹包問題的進階版
因為資料量大,所以不能用三重迴圈以及二維陣列
所以可以將物品的體積和價值利用二進位制形式存起來
然後再進行一維優化即可

題目程式碼

#include <iostream>
#include <algorithm>

using namespace std;
const int N = 2010, M = 50010;
int v[M], w[M];
int f[N];
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] = a * k;
            w[cnt] = b * k;
            s -= k;
            k *= 2;
        }
        if(s > 0)
        {
            cnt ++ ;
            v[cnt] = a * s;
            w[cnt] = b * s;
        }
    }
    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;
}