0-1背包问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i < 40; i++)
            {
               (new MaxBag()).main(null);
                Console.WriteLine("----------------------------------------");
            }
            Console.Read();
        }
    }
    public class MaxBag
    {
         int n;           // 描述物品个数
         int c;           // 描述背包容量
         int[] value;     // 描述物品价值
        int[] weight;    // 描述物品重量

        public  void main(String[] args) {
        // 初始赋值操作
        value = new int[]{1500, 3000, 2000,2000};
        weight = new int[]{1, 4, 3,1};

        var rnd = new Random(Environment.TickCount);
        var index=rnd.Next(0, 3);
        var temp = value[0];
        value[0] = value[index];
        value[index] = temp;
        temp = weight[0];
        weight[0] = weight[index];
        weight[index] = temp;

        c =5;
        n = value.Length;

        // 构造最优解的网格:3行4列
        int[][] maxValue = new int[n][];
        for (int i = 0; i < n; i++)
        {
            maxValue[i] = new int[c];
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < c; j++) {
                maxValue[i][j] = 0;
            }
        }   // end for

        // 填充网格
        for (int i = 0; i < n; i++) {
            for (int j = 1; j <= c; j++) {
                if (i == 0) {
                    maxValue[i][j - 1] = (weight[i] <= j ? value[i] : 0);
                } else {
                    int topValue = maxValue[i - 1][j - 1];  // 上一个网格的值
                    int thisValue = (weight[i] <= j ?       // 当前商品的价值 + 剩余空间的价值
                            (j - weight[i] > 0 ? value[i] + maxValue[i - 1][j - weight[i]-1] : value[i])
                            : topValue);

                    // 返回 topValue和thisValue中较大的一个
                    maxValue[i][j - 1] = (topValue > thisValue ? topValue : thisValue);
                }   // end if
            }   // end inner for
        }   // end outer for

        // 打印结果二维数组maxValue
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < c; j++) {
                Console.Write( P(maxValue[i][j]) + "    ");
            }
            Console.WriteLine();
        }
    }

        private String P(int v)
        {
            var strV = v.ToString();
            var len = strV.Length;
             strV = ("          " + strV);
             strV=strV.Substring(strV.Length-5);
             return strV;
        }

    }
    
}
View Code

注意每个物品只能取一次,所以剩余空间的最优价值存储在上一行,本行可能包含了当前物品,这会导致同一物品取2次,另外剩余物品最优价值的列是[j-weight[i]-1]

参考

https://www.jianshu.com/p/a66d5ce49df5

原文地址:https://www.cnblogs.com/wdfrog/p/12871311.html