[C#] C#动态规划解决0-1背包问题 →→→→→进入此内容的聊天室

来自 , 2020-10-18, 写在 C#, 查看 136 次.
URL http://www.code666.cn/view/ccc36675
  1. // 利用动态规划解决0-1背包问题
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6.  
  7.  
  8. namespace Knapsack_problem  // 背包问题关键在于计算不超过背包的总容量的最大价值
  9. {
  10.     class Program
  11.     {
  12.         static void Main()
  13.         {
  14.             int i;
  15.             int capacity = 16;
  16.             int[] size = new int[] { 3, 4, 7, 8, 9 };// 5件物品每件大小分别为3, 4, 7, 8, 9 且是不可分割的  0-1 背包问题
  17.             int[] values = new int[] { 4, 5, 10, 11, 13 };//// 5件物品每件的价值分别为4, 5, 10, 11, 13
  18.             int[] totval = new int[capacity + 1];  // 数组totval用来存贮最大的总价值
  19.             int[] best = new int[capacity + 1];    // best 存贮的是当前价值最高的物品
  20.             int n = values.Length;
  21.             for (int j = 0; j <= n - 1; j++)
  22.                 for (i = 0; i <= capacity; i++)
  23.                     if (i >= size[j])
  24.                         if (totval[i] < (totval[i - size[j]] + values[j])) // 如果当前的容量减去J的容量再加上J的价值比原来的价值大,就将这个值传给当前的值
  25.                         {
  26.                             totval[i] = totval[i - size[j]] + values[j];
  27.                             best[i] = j;                                  // 并把j传给best
  28.                         }
  29.             Console.WriteLine("背包的最大价值: " + totval[capacity]);
  30.             //   Console.WriteLine("构成背包的最大价值的物品是: " );
  31.             //    int totcap = 0;
  32.  
  33.  
  34.             //  while (totcap <= capacity)
  35.             //   {
  36.             //     Console.WriteLine("物品的大小是:" + size[best[capacity - totcap]]);
  37.             //     for (i = 0; i <= n-1; i++)
  38.             //     totcap += size[best[i]];
  39.             //  }
  40.  
  41.  
  42.         }
  43.     }
  44. }
  45. //csharp/7208

回复 "C#动态规划解决0-1背包问题"

这儿你可以回复上面这条便签

captcha