This article describes the method of using dynamic programming to solve the 0-1 backpack problem in C#. Share it for your reference. The details are as follows:
// Use dynamic programming to solve the 0-1 backpack problemusing System; using ; using ; using ; namespace Knapsack_problem // The key to the backpack problem is to calculate the maximum value of the total capacity of the backpack.{ class Program { static void Main() { int i; int capacity = 16; int[] size = new int[] { 3, 4, 7, 8, 9 }; // Each of the 5 items is 3, 4, 7, 8, 9 in size respectively //And it is inseparable 0-1 Backpacking problem int[] values = new int[] { 4, 5, 10, 11, 13 }; // Each of the 5 items is 4, 5, 10, 11, 13 respectively int[] totval = new int[capacity + 1]; // Array Totval is used to store the maximum total value int[] best = new int[capacity + 1]; // Best stores the most valuable items currently int n = ; 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])) // If the current capacity minus J's capacity plus J's value is greater than the original value, // Pass this value to the current value { totval[i] = totval[i - size[j]] + values[j]; best[i] = j; // and pass j to best } ("The greatest value of a backpack: " + totval[capacity]); // ("The items that make up the backpack are: "); // int totcap = 0; // while (totcap <= capacity) // { // ("The size of the item is:" + size[best[capacity - totcap]]); // for (i = 0; i <= n-1; i++) // totcap += size[best[i]]; // } } } }
I hope this article will be helpful to everyone's C# programming.