0-1背包问题

package com.cjs.zeroonepackage;

public class ZeroOnePackage {


    /**
     * 计算0-1背包问题
     * 
     * @param w
     *            传入的背包重量数组
     * @param v
     *            传入的背包价值数组
     * @param c
     *            传入的背包总容量
     * @return maxValue[n][c] 背包能装物品的最大价值
     */
    public static int zeroOnePackage(int w[], int v[], int c) {

        int n = w.length; //物品的数量
        int[][] maxValue = new int[n + 1][c + 1]; //存储放入背包中物品价值的数组

        // 初始化
        for (int i = 0; i <= n; i++) {
            maxValue[i][0] = 0;
        }
        for (int i = 0; i <= c; i++) {
            maxValue[0][i] = 0;
        }

        for (int i = 1; i <= n; i++) {
            int t = w[i - 1] > c ? c : w[i - 1]; //防止出现物品重量比背包总容量大而出现问题
            for (int j = 1; j < t; j++) { //背包剩余容量比物品重量小时,不放入
                maxValue[i][j] = maxValue[i - 1][j];
            }
            for (int j = w[i - 1]; j <= c; j++) { ////背包剩余容量比物品重量大时,放入
                maxValue[i][j] = Math.max(maxValue[i - 1][j], maxValue[i - 1][j
                        - w[i - 1]]
                        + v[i - 1]);
            }
        }

        return maxValue[n][c];

    }

}

C++实现

#include <iostream>
using namespace std;
int zeroOnePackage(int w[],int v[],int c,int n)
{

    int maxValue[n+1][c+1];

    //初始化
    for(int i = 0; i <= n; i++)
    {
        maxValue[i][0] = 0;
    }
    for(int i = 0; i <= c; i++ )
    {
        maxValue[0][i] = 0;
    }

    for(int i = 1; i <= n; i++)
    {
        int t = w[i-1] > c ? c:w[i-1];
        for(int j = 1; j < t; j++)
        {
            maxValue[i][j] = maxValue[i-1][j];
        }
        for(int j = w[i-1]; j <= c; j++ )
        {
            maxValue[i][j] = max(maxValue[i-1][j], maxValue[i-1][j-w[i-1]]+v[i-1]);
        }
    }

    return maxValue[n][c];

}

int main()
{
    int n,c;
    int w[2000],v[2000];
    while(cin>>c>>n)
    {
        for(int i = 0; i < n; i++)
        {
            cin>>w[i]>>v[i];

        }

        cout<<"Result:"<<zeroOnePackage(w,v,c,n)<<endl;


    }
    return 0;
}
原文地址:https://www.cnblogs.com/cjshuang/p/5397778.html