有界背包的DP算法?

时间:2012-03-04 23:02:00

标签: algorithm knapsack-problem

关于背包问题的Wikipedia article包含三种类型的列表:

  1. 1-0(一种类型的一项)

  2. 有界(几种类型的物品)

  3. 无界限(无限数量的某类物品)

  4. 本文包含针对1.和3.类型问题的DP方法,但没有针对2的解决方案。

    如何描述用于求解的动态规划算法?

6 个答案:

答案 0 :(得分:8)

使用0-1变体,但允许重复解决方案中的项目,直到其绑定中指定的次数。您需要维护一个向量,说明您已在部分解决方案中包含的每个项目的副本数。

答案 1 :(得分:5)

提到的其他DP解决方案都不理想,因为它们要求您直接模拟问题,从而导致O(number of items * maximum weight * total count of items)的运行时复杂性。

有很多方法可以对此进行优化,在这里我将提及其中的一些:


一种解决方案是应用类似于Sqrt分解的技术,并在此处进行说明:https://codeforces.com/blog/entry/59606。该算法在O(number of items * maximum weight * sqrt(maximum weight))中运行。


但是,Dorijan Lendvaj在https://codeforces.com/blog/entry/65202?#comment-492168

处描述了一种运行速度更快的算法,该算法在O(number of items * maximum weight * log(maximum weight))中运行

想到上述方法的另一种方法是:

对于每种类型的商品,让我们定义以下值:

  • w,当前商品类型的重量/费用
  • v,当前项目类型的值
  • n,可使用的当前类型物品的副本数

阶段1

首先,让我们考虑2^k,它是2的最大幂小于或等于n。我们插入以下项目(每个插入的项目的格式为(weight, value)):(w, v)(2 * w, 2 * v)(2^2 * w, 2^2 * v),...,(2^(k-1) * w, 2^(k-1) * v)。请注意,每个插入的项目分别代表当前类型的项目的2^02^1,...,2^(k-1)个副本。

观察到这与插入当前项目类型的2^k - 1副本相同。这是因为我们可以通过采用与n'的二进制表示相对应的上述各项的组合来模拟任意数量的项(表示为n')的取整(对于所有整数{{1 }},如果设置了代表k'的位,则获取代表当前类型的2^k'个副本的项目。

第二阶段

最后,我们只插入与2^k'的设置位相对应的项目。 (对于所有整数n - (2^k - 1),如果设置了代表k'的位,则插入2^k'。)

现在,我们可以简单地通过组合上述插入的项目来模拟最多(2^k' * w, 2^k' * v)个当前类型的项目。

我目前尚无此解决方案的确切证明,但是在试用了一段时间后,它似乎是正确的。如果可以弄清楚,我可以稍后再更新此帖子。

证明

首先,一个命题:我们需要证明的是,插入上述项目使我们可以模拟采用任何数量的当前类型的项目,直到n

考虑到这一点,让我们定义一些变量:

  • n为当前可用类型的项目数
  • n为我们要采用的当前类型的物品数
  • x为最大整数,使k

如果是2^k <= n,我们可以使用算法第1阶段中描述的方法轻松提取x < 2^k项:

...我们可以通过采用与n'的二进制表示相对应的上述各项的组合来模拟任意数量的项(表示为n')(对于所有整数k',如果该位代表2 ^ k'的商品已设置,请选择代表当前类型的商品的2 ^ k'副本的商品。

否则,我们将执行以下操作:

x个项目。这是通过取出阶段2中插入的所有项目来完成的。现在只有阶段1中插入的​​项目可供使用。

n - (2^k - 1)个项目。由于此值始终小于x - (n - (2^k - 1)),因此我们只能使用第一种情况下使用的方法。

最后,我们怎么知道2^k

如果我们简化左侧,则会得到:

x - (n - (2^k - 1)) < 2^k x - (n - (2^k - 1)) x - n + 2^k - 1

如果以上值为x - (n + 1) + 2^k,则>= 2^k为true,表示x - (n + 1) >= 0。这将是不可能的,因为这不是x > n的有效值。


最后,甚至有一种提到的方法herex时间内运行。

该算法与提出的蛮力方法ic3b3rg类似,仅使用简单的DP优化和滑动窗口双端队列来缩短运行时间。

我的代码已针对以下问题(经典有界背包问题)进行了测试:https://dmoj.ca/problem/knapsack

我的代码:https://pastebin.com/acezMrMY

答案 2 :(得分:3)

我在代码项目上发布了an article,它讨论了一种更有效的有界背包算法解决方案。

来自文章:

  

在动态编程解决方案中,m数组的每个位置都是a   能力的子问题j。在0/1算法中,针对每个子问题   我们考虑将每个项目的一个副本添加到背包中的价值。   在以下算法中,对于每个子问题,我们考虑该值   添加适合的数量或数量中的较小者   每个项目都有。

     

我还增强了代码,以便我们可以确定代码中的内容   优化的背包(而不是优化的值)。

ItemCollection[] ic = new ItemCollection[capacity + 1];

for(int i=0;i<=capacity;i++) ic[i] = new ItemCollection();

for(int i=0;i<items.Count;i++)
  for(int j=capacity;j>=0;j--)
    if(j >= items[i].Weight) {
      int quantity = Math.Min(items[i].Quantity, j / items[i].Weight);
      for(int k=1;k<=quantity;k++) {
        ItemCollection lighterCollection = ic[j - k * items[i].Weight];
        int testValue = lighterCollection.TotalValue + k * items[i].Value;
        if(testValue > ic[j].TotalValue) (ic[j] = lighterCollection.Copy()).AddItem(items[i],k);
      }
    }

private class Item {

  public string Description;
  public int Weight;
  public int Value;
  public int Quantity;

  public Item(string description, int weight, int value, int quantity) {
    Description = description;
    Weight = weight;
    Value = value;
    Quantity = quantity;
  }

}

private class ItemCollection {

  public Dictionary<string,int> Contents = new Dictionary<string,int>();
  public int TotalValue;
  public int TotalWeight;

  public void AddItem(Item item,int quantity) {
    if(Contents.ContainsKey(item.Description)) Contents[item.Description] += quantity;
    else Contents[item.Description] = quantity;
    TotalValue += quantity * item.Value;
    TotalWeight += quantity * item.Weight;
  }

  public ItemCollection Copy() {
    var ic = new ItemCollection();
    ic.Contents = new Dictionary<string,int>(this.Contents);
    ic.TotalValue = this.TotalValue;
    ic.TotalWeight = this.TotalWeight;
    return ic;
  }

}

Code Project文章中的下载包括一个测试用例。

答案 3 :(得分:2)

  • 首先,将所有数据存储在一个数组中(重复)。
  • 然后使用维基百科文章(1-0)中提到的第一种方法。

例如,尝试使用{2(2次),4次(3次),...}的有界背包相当于使用{2,2,4,4,4,...来解决1-0背包。 ..}。

答案 4 :(得分:1)

我建议你使用背包分数贪婪方法算法。它的复杂性是O(n log n),也是最好的算法之一。 下面我在c#中提到了它的代码。

 private static void Knapsack()
        {
            Console.WriteLine("************Kanpsack***************");
            Console.WriteLine("Enter no of items");
            int _noOfItems = Convert.ToInt32(Console.ReadLine());

            int[] itemArray = new int[_noOfItems];
            int[] weightArray = new int[_noOfItems];
            int[] priceArray = new int[_noOfItems];
            int[] fractionArray=new int[_noOfItems];

            for(int i=0;i<_noOfItems;i++)
            {
                Console.WriteLine("[Item"+" "+(i+1)+"]");
                Console.WriteLine("");
                Console.WriteLine("Enter the Weight");
                weightArray[i] = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter the Price");
                priceArray[i] = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("");
                itemArray[i] = i+1 ;

            }//for loop

            int temp;
            Console.WriteLine("       ");
            Console.WriteLine("ITEM" + "         " + "WEIGHT" + "         "+"PRICE");
            Console.WriteLine("       ");
            for(int i=0;i<_noOfItems;i++)
            {
                Console.WriteLine("Item"+" "+(i+1)+"       "+weightArray[i]+"               "+priceArray[i]);
                Console.WriteLine(" ");
            }//For Loop For Printing the value.......


            //Caluclating Fraction for the Item............

            for(int i=0;i<_noOfItems;i++)
            {
                fractionArray[i] = (priceArray[i] / weightArray[i]);
            }
            Console.WriteLine("Testing.............");

            //sorting the Item on the basis of fraction value..........

            //Bubble Sort To Sort the Process Priority

            for (int i = 0; i < _noOfItems; i++)
            {
                for (int j = i + 1; j < _noOfItems; j++)
                {
                    if (fractionArray[j] > fractionArray[i])
                    {
                        //item Array
                        temp = itemArray[j];
                        itemArray[j] = itemArray[i];
                        itemArray[i] = temp;

                        //Weight Array
                        temp = weightArray[j];
                        weightArray[j] = weightArray[i];
                        weightArray[i] = temp;

                        //Price Array
                        temp = priceArray[j];
                        priceArray[j] = priceArray[i];
                        priceArray[i] = temp;

                        //Fraction Array
                        temp = fractionArray[j];
                        fractionArray[j] = fractionArray[i];
                        fractionArray[i] = temp;





                    }//if
                }//Inner for
            }//outer For

            // Printing its value..............After Sorting..............
            Console.WriteLine("       ");
            Console.WriteLine("ITEM" + "         " + "WEIGHT" + "         " + "PRICE" + "         "+"Fraction");
            Console.WriteLine("       ");
            for (int i = 0; i < _noOfItems; i++)
            {
                Console.WriteLine("Item" + " " + (itemArray[i]) + "      " + weightArray[i] + "               " + priceArray[i] + "             "+fractionArray[i]);
                Console.WriteLine(" ");
            }//For Loop For Printing the value.......

            Console.WriteLine("");
            Console.WriteLine("Enter the Capacity of Knapsack");
            int _capacityKnapsack = Convert.ToInt32(Console.ReadLine());

            // Creating the valuse for Solution

               int k=0;
               int fractionvalue = 0;
               int[] _takingItemArray=new int[100];

               int sum = 0,_totalPrice=0;
               int l = 0;

               int _capacity = _capacityKnapsack;
              do
              {
                  if(k>=_noOfItems)
                  {
                      k = 0;
                  }

                  if (_capacityKnapsack >= weightArray[k])
                  {
                      _takingItemArray[l] = weightArray[k];
                      _capacityKnapsack = _capacityKnapsack - weightArray[k];
                      _totalPrice += priceArray[k];
                      k++;
                      l++;
                  }
                  else
                  {
                      fractionvalue = fractionArray[k];
                      _takingItemArray[l] = _capacityKnapsack;
                      _totalPrice += _capacityKnapsack * fractionArray[k];
                      k++;
                      l++;

                  }
                  sum += _takingItemArray[l-1];
              } while (sum != _capacity);
              Console.WriteLine("");
              Console.WriteLine("Value in Kg Are............");
              Console.WriteLine("");
              for (int i = 0; i < _takingItemArray.Length; i++)
              {
                  if(_takingItemArray[i]!=0)
                  {
                      Console.WriteLine(_takingItemArray[i]);
                      Console.WriteLine("");
                  }
                  else
                  {
                      break;
                  }
enter code here
              }//for loop
              Console.WriteLine("Toatl Value is "+_totalPrice);

            }//Method

答案 5 :(得分:-1)

我们可以使用0/1背包算法跟踪每个商品剩余的商品数量;

我们也可以对无限制背包算法进行同样的处理,以解决有限制背包问题。

相关问题