欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#使用动态规划解决0-1背包问题实例分析

程序员文章站 2022-06-09 13:45:50
本文实例讲述了c#使用动态规划解决0-1背包问题的方法。分享给大家供大家参考。具体如下: // 利用动态规划解决0-1背包问题 using system; u...

本文实例讲述了c#使用动态规划解决0-1背包问题的方法。分享给大家供大家参考。具体如下:

// 利用动态规划解决0-1背包问题
using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace knapsack_problem
// 背包问题关键在于计算不超过背包的总容量的最大价值
{
 class program
 {
  static void main()
  {
   int i;
   int capacity = 16;
   int[] size = new int[] { 3, 4, 7, 8, 9 };
   // 5件物品每件大小分别为3, 4, 7, 8, 9 
   //且是不可分割的 0-1 背包问题
   int[] values = new int[] { 4, 5, 10, 11, 13 };
   // 5件物品每件的价值分别为4, 5, 10, 11, 13
   int[] totval = new int[capacity + 1];
   // 数组totval用来存贮最大的总价值
   int[] best = new int[capacity + 1];
   // best 存贮的是当前价值最高的物品
   int n = values.length;
   for (int j = 0; j <= n - 1; j++)
    for (i = 0; i <= capacity; i++)
     if (i >= size[j])
      if (totval[i] < (totval[i - size[j]] + values[j]))
   // 如果当前的容量减去j的容量再加上j的价值比原来的价值大,
   //就将这个值传给当前的值
      {
       totval[i] = totval[i - size[j]] + values[j];
       best[i] = j; // 并把j传给best
      }
   console.writeline("背包的最大价值: " + totval[capacity]);
   // console.writeline("构成背包的最大价值的物品是: " );
   // int totcap = 0;
   // while (totcap <= capacity)
   // {
   //  console.writeline("物品的大小是:" + size[best[capacity - totcap]]);
   //  for (i = 0; i <= n-1; i++)
   //  totcap += size[best[i]];
   // }
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。