c_cpp 01 KnapSack

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 01 KnapSack相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

void knapsack(int w[], int v[], int n, int W){
    int res[n+1][W+1];
    for(int i=0; i<=n; i++)
        res[i][0] = 0;
    for(int i=0; i<=W; i++)
        res[0][i] = 0;
    for(int i=1; i<=n; i++){
        for(int j=1; j<=W; j++){
            if(w[i-1] > j)
                res[i][j] = res[i-1][j];
            else
                res[i][j] = max((v[i-1]+res[i-1][j-w[i-1]]), (res[i-1][j]));
        }
    }
    vector <int> sol;
    int i=n, j=W;
    while(i>0 && j>0){
        //cout << i << j << endl;
        if(res[i][j] != res[i-1][j]){
            sol.push_back(w[i-1]);
            j-=w[i-1];
            i--;
        }
        else i--;

    }
    cout << "maximum possible value is " << res[n][W] << endl;
    cout << "the selected weights are ";
    for(i=sol.size()-1; i>=0; i--) cout << sol[i] << " ";
}

int main(){
    int n, W;
    cout << "Enter no. of items" << endl;
    cin >> n;
    int w[n],v[n];
    cout << "Enter weights of items" << endl;
    for(int i=0; i<n; i++)
        cin >> w[i];
    cout << "Enter values of items" << endl;
    for(int i=0; i<n; i++)
        cin >> v[i];
    cout << "Enter max weight" << endl;
    cin >> W;
    knapsack(w,v,n,W);
    return 0;
}

以上是关于c_cpp 01 KnapSack的主要内容,如果未能解决你的问题,请参考以下文章

(01背包 当容量特别大的时候) Knapsack problem (fzu 2214)

Atcoder E - Knapsack 2 (01背包进阶版 ex )

knapsack

knapsack() 向量长度问题

FZU 2214 Knapsack problem (01背包)

如何在 KnapSack 问题中显示所有包含的数字?