0-1背包问题(0-1 knapsack)

#include <iostream>
#include <cstdio>

using namespace std;
/***********************
 *  writer: HangFeiYu  *
 *   date: 2017/9/28   *
 **********************/

void knapSack(int width, int n, int w[], int v[])  //w is the capacity of knapSack, the m I uesd when calling function is 11, because the we need m = 10, so the width of array should be 11. n is the number of thing
{
    int c[n+1][width], x[n+1];  //x is the result of problem, it record which thing is put into the knapsack
    for(int i=0; i<=n; i++)  //the value of item that can be put when backpack capacity is zero is also zero
    {
        c[i][0] = 0;
    }

    for(int i=0; i<width; i++)  //the value of item that can be put when the number of item is zero is also zero
    {
        c[0][i] = 0;
    }
    for(int i=1; i<=n; i++)  //put n items in turn
    {
        for(int j=1; j<width; j++)  //knapsack capacity grow from small to large
        {
            if(j<w[i])  //if the knapsack capacity is smaller than  weight of weight
                c[i][j] = c[i-1][j];
            else  //if the knapsack capacity is bigger than  weight of weight
                c[i][j] = max(c[i-1][j], c[i-1][j-w[i]]+v[i]);  //judgement plus the i-th item and not the i-th item which is larger
        }
    }

    for(int i=0; i<=n; i++)  //here i output the two-dimensional array
    {
        for(int j=0; j<width; j++)
        {
            cout << c[i][j] << " ";
        }
        cout << endl;
    }


    int j = width - 1;  //because the width is the maximum capacity of knapsack plus 1
    for(int i=n; i>0; i--)
    {
        if(c[i][j]>c[i-1][j])  //if the i-th item is put into knapsack,x[i] = 1, otherwise x[i] = 0;the weigt of knap should back to j-w[i]
        {
            x[i] = 1;
            j = j- w[i];
        }

        else
            x[i] = 0;
    }

    for(int i=1; i<=n; i++)
        cout << x[i] << " ";
    cout << endl << c[n][width-1];

}



int main(void)
{
    int v[] = {0, 6, 3, 5, 4, 6};
    int w[] = {0, 2, 2, 6, 5, 4};
    knapSack(11, 5, w, v);
    return 0;
}

 

posted @ 2017-09-28 20:36  diamondDemand  阅读(440)  评论(0)    收藏  举报