I posted an article in a draft code that discusses a more efficient solution to the limited backpack algorithm.
From the article:
In a dynamic programming solution, each position of the array m is a sub-problem of capacity j. In the 0/1 algorithm for each sub-task, we consider the value of adding one copy of each element to the backpack. In the following algorithm, for each subtask, we consider the value of adding a smaller amount that will correspond, or the amount available for each element.
I also improved the code so that we can define that in an optimized backpack (as opposed to just an optimized value).
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; } }
The download in the Project Code article includes a test case.
ic3b3rg
source share