Description:
There are six kinds of jewelry with different values. Ask if you can divide these jewelry into two equal values. Of course, each jewelry cannot be cut.
Obviously, this is a backpack problem. Due to the huge number of jewels, we need to split jewelry of the same value in binary format to improve program efficiency, this can quickly reduce the number of jewelry (specifically, the number of jewelry will become the order of magnitude of O (logN), and N is the number of the original jewelry). The binary split is equivalent to the original one, think about the binary number.
01 The state transition equation of the backpack is:
When v <Ci f [I, v] = f [I-1, v]; (1)
When v> = Ci f [I, v] = Max (f [I-1, v], f [I-1, v-Ci] + Wi); (2) // when the I-th item can be put down, we can choose to put it or not, depending on the total value.
V indicates the medium capacity of the current backpack, Ci indicates the volume of the I-th item, Wi indicates the value of the I-th item, f [I, v] indicates the maximum value of a backpack with a capacity of v after considering the first I items.
To implement the above state transition equation, we need to open a two-dimensional array of I * V (I is the total number of items, and V is the total volume of the backpack ), however, sometimes I and V may be very large, so we need a lot of space or even out of scope. In fact, when we only consider the final value and do not care about the items selected, the space of the above transfer equation can be compressed. We can see that when considering item I, the state we use is only related to the item in the I-1, so the state transition equation of space compression is:
When v <Ci, f [v] = f [v]; (3)
When v> = Ci, f [v] = Max (f [v], f [v-Ci] + Wi); (4)
When using (4), the order of solution is very important. To ensure that the preceding state is not overwritten, We need to calculate values from the largest to the smallest.
Here we will talk about binary splitting www.2cto.com
Assume that the number of jewelry in a certain category is N. We can split N into 1, 2, 4, 8 ,......, 2 ^ (k-1), N-2 ^ k + 1. The split numbers can represent 1 ~ Any number between N.
In this way, we reduce the number of items to logN (based on 2 and rounded up ).
Author: HooLee