One of dynamic programming: knapsack problem

01 backpack

Given n items, a backpack with a capacity of m. Each item has two attributes, vi is value, wi is weight, and each item can only be used once.

int main()
{
    
    
    int v[110], w[110];
    int f[110];
    int n, m;    
    cin >> n >> m;
    for(int i = 1; i <= n; i ++) cin >> v[i] >> w[i];
    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;
}

Complete backpack

Given n items, a backpack with a capacity of m. Each item has two attributes, vi is value, wi is weight, and each item can be used multiple times.

int main() {
    
    
    int v[110], w[110];
    int f[110];
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> v[i] >> w[i];
    for (int i = 1; i <= n; i++)
        for (int j = v[i]; j <= m; j++)
                f[j] = max(f[j], f[j - v[i]] + w[i]);
    cout << f[m] << endl;
}

Multiple backpack

Given n items, a backpack with a capacity of m. Each item has two attributes, vi is value, wi is weight, and each item can be used a specified number of times.

int main()
{
    
    
    int v[2010], w[2010];
    int f[2010];
    int n, m;
    int cnt = 0;
    cin >> n >> m;
    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;
}

Guess you like

Origin blog.csdn.net/qq_47783181/article/details/112690953