Today stroll the garden, accidentally saw the "knapsack problem", so the Internet to find the relevant information, and wrote a simple implementation Plan.
What is a backpack problem?
Simple to understand, is to give a pile of goods and a bag, each item has the corresponding weight and value, the package has its own load. All we have to do is to load the bag with the highest amount of value in the Package.
How to solve Knapsack problem?
In general, recursive method is used to model each item in Mathematics. Each time you place an item there are two options (provided that the item can be placed):
1. When the item is placed, the problem is converted, minus the weight of the item, and the maximum amount of items that can be loaded with the remaining Capacity.
2. If the item is not placed, then the problem is converted to the weight of the item, and the capacity of the package can be loaded with the maximum value of the Item.
For ease of understanding, you can refer to the following table (capacity of the first behavior pack):
| Weight |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
Value |
| 2 |
0 |
0 |
5 |
5 |
5 |
5 |
5 |
5 |
5 |
5 |
5 |
5 |
| 5 |
0 |
0 |
5 |
5 |
5 |
6 |
6 |
11 |
11 |
11 |
11 |
6 |
| 3 |
0 |
0 |
5 |
5 |
6 |
6 |
6 |
11 |
11 |
11 |
12 |
1 |
| 7 |
0 |
0 |
5 |
5 |
6 |
6 |
6 |
16 |
16 |
21st |
21st |
16 |
| 8 |
0 |
0 |
5 |
5 |
6 |
6 |
6 |
16 |
16 |
21st |
21st |
10 |
Take the data section, the data in row fourth, column eighth,
If item three is placed, the maximum value is 1 (item three Value) +5 (load-bearing is the highest value of 4 O'clock) = 6.
If item three is not placed, the maximum value is 11 (load-bearing is 7 o'clock put the highest value of the front Item)
The code is as Follows:
Item Category
public class bagitem{ publicintgetset;} public int Get Set ; }}
Backpack class
public classbag{PrivateList<bagitem>_items; Private int_capacity; publicBag (list<bagitem> items,intCapacity) { this. _items =items; this. _capacity =capacity; } public intcalculatemaxvalue () {intn =_items. Count; int[,] array =New int[n +1, _capacity +1]; for(inti =0; I < n +1; i++) {array[i,0] =0; } for(inti =0; I < _capacity +1; i++) {array[0, i] =0; } for(inti =1; I < n +1; i++) { for(intj =1; J < _capacity +1; J + +) { if(_items[i-1]. Weight >j) {array[i, j]= array[i-1, j]; } Else{array[i, j]= Math.max ((_items[i-1]. Value + array[i-1, j-_items[i-1]. Weight]), array[i-1, j]); } } } returnarray[n, _capacity]; }}
This is where the knapsack problem is Realized.
Algorithm essay one (knapsack Problem)