0-1 knapsack problem0-1 Basic idea of knapsack problem:P[i,j] Represents the maximum value of the value of J when the total value of the first I item, Str[i, J] represents the value of the item weight string when the total value of the first I item is the maximum value of J. i=0 or j=0:p[i, j] = 0;
Str[i, J] = "";
Article I items can be placed in the backpack when the weight is less than J
p[i, j] = P[i-1, j-w[i-1]] + v[i-1] > p[i-1, j]? P[i-1, J-w[i-1]] + v[i-1]: P[i-1, J];
Str[i, j] = P[i-1, j-w[i-1]] + v[i-1] > p[i-1, j]? Str[i-1, J-w[i-1]] + w[i-1]. ToString (): Str[i-1,j];
Article I items can not be put into the backpack when the weight is greater than J:
P[i, j] = P[i, j-1];
Str[i, J] =str[i-1,j];
The code is as follows:Class Program
{
0-1 knapsack problem
static void Main (string[] args)
{
int[] W = {2,2,6,5,4};
Int[] v = {6, 3, 5, 4, 6};
string[,] str = getpackage (w,v,10);
for (int i = 0; i < str. GetLength (0); i++)
{
for (int j = 0; j < Str. GetLength (1); J + +)
Console.WriteLine (i+ "" +j+ "into the cargo Weight:" +str[i,j]);
}
Console.read ();
}
Static string[,] Getpackage (int[] W, int[] v, int maxweight)
{
int[,] p = new Int[w.length + 1, maxweight + 1];
string[,] str = new String[w.length + 1, maxweight + 1];
for (int i = 0; i < p.getlength (0); i++)
{
for (int j = 0; J < p.getlength (1); j + +)
{
if (i = = 0 | | j = 0)
{
P[i, j] = 0;
Str[i, J] = "";
}
Else
{
if ((j-w[i-1)) >= 0)//Article I items in weight less than equals J can be put into the backpack
{
P[i, j] = P[i-1, j-w[i-1]] + v[i-1] > p[i-1, j]? P[i-1, J-w[i-1]] + v[i-1]: P[i-1, J];
Str[i, j] = P[i-1, j-w[i-1]] + v[i-1] > p[i-1, j]? Str[i-1, J-w[i-1]] + w[i-1]. ToString (): Str[i-1,j];
}
else//article I items in weight greater than J can not be placed in the backpack, at this time the total value of weight of j-1 when the total value, the total cargo is not placed in the article I item of the total goods
{
P[i, j] = P[i, j-1];
Str[i, J] =str[i-1,j];
}
}
}
}
return str;
}
}
test results such as:
C # 0-1 Knapsack problem