Multiknapsack算法 - 在尝试删除对象

时间:2016-07-28 14:25:31

标签: c# algorithm

我在使用多背包解算器时遇到了这个问题。 该程序在一个背包上运行良好,但是当遇到多个问题时,存在一些问题。

问题:项目未从收藏中删除。我知道我需要这样做,因为对于第二个背包,它再次通过相同的对象进行迭代 - 所以最大化的val是相同的......

private void Knapsack()
{
    List<Plecak> descendingKanps = _plecakList.OrderByDescending(o => o.W).ToList(); // List of configured Kanpsacks in descending order
    List<Produkt> descendingProducts = _produktList.OrderByDescending(o => o.cena).ToList(); // List of products to pack in descending order
    int N = descendingProducts.Count; //number of items in product list
    double maxVal = 0; // accumulated value of one knapsack
    foreach (Plecak p in descendingKanps) // for every knapsack...
    {
        double[,] V = new double[N + 1, (int)p.W + 1]; //array that stores best option (the value of item)
        for (int c = 0; c <= p.W; c++) //since its a 0-1 MKP problem so initialize whole array with zeroes
        {
            V[0, c] = 0;
        }
        for (int r = 0; r <= N; r++)
        {
            V[r, 0] = 0;
        }

        for (int i = 1; i <= N; i++) // constraint of items count
        {
            for (int wt = 1; wt <= p.W; wt++) //the constraint of weight
            {
                if (descendingProducts[i - 1].waga < wt + 1) // if weight of the product is less than constraint, so it can be added...
                    V[i, wt] = Math.Max(descendingProducts[i - 1].cena + V[i - 1, wt - descendingProducts[i - 1].waga], V[i - 1, wt]); // find best solution and add the value to the Value array, comapre the value with the value form previous row
                else
                    V[i, wt] = V[i - 1, wt]; // keep 0, or last best solution

                maxVal = V[i, wt]; // assign to variable
            }
        }
        summary.Items.Add("maximum val for knapsack: " + p.nazwa + " is: " + maxVal); // print out the value of knapsack
    }
}

1 个答案:

答案 0 :(得分:0)

这有望成为一个答案,但现在这是一个问题。

在你的代码中你有这个:

break

你说你“用零来初始化整个数组”。上面的代码将对数组执行此操作:

0 0 0 0 0
0 1 1 1 1
0 1 1 1 1
0 1 1 1 1

您只能到达第一列和第一行。如果数组中的所有位置都应更改为for (int c = 0; c <= p.W; c++) //since its a 0-1 MKP problem so initialize whole array with zeroes { V[0, c] = 0; } for (int r = 0; r <= N; r++) { V[r, 0] = 0; } ,那么这是正确的方法:

0

我希望这些意见可以提供帮助。