本文實例講述了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#程序設計有所幫助。
新聞熱點
疑難解答