This article mainly introduces PHP dynamic planning to solve the 0-1 knapsack problem. The example analyzes the principle and implementation skills of the knapsack problem, for more information about PHP dynamic planning, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
Backpack problem description: a backpack with a maximum weight of W now has n items, each with a weight of t and the value of each item is v.
To maximize the weight of this backpack (but not more than W), and at the same time, the greatest value of the backpack is required.
Idea: define a two-dimensional array, one-dimensional is the number of items (indicating each item), two-dimensional is the weight (no more than the maximum, here is 15), the following array,
Max (i-1, w), wi + opt (i-1, w-wi,
Opt (i-1, w-wi) refers to the previous optimal solution
<? Php // This is what I wrote based on dynamic programming principles // max (opt (i-1, w), wi + opt (i-1, w-wi )) // the maximum weight of a backpack is $ w = 15; // here there are four items, the weight of each item $ dx = array (3, 4, 5, 6 ); // the value of each item $ qz = array (8, 7, 4, 9); // defines an array $ a = array (); // initializes for ($ I = 0; $ I <= 15; $ I ++) {$ a [0] [$ I] = 0;} for ($ j = 0; $ j <= 4; $ j ++) {$ a [$ j] [0] = 0;} // opt (i-1, w), wi + opt (i-1, w-wi) for ($ j = 1; $ j <= 4; $ j ++) {for ($ I = 1; $ I <= 15; $ I ++) {$ a [$ j] [$ I] = $ a [$ j-1] [$ I]; // w = 15 if ($ dx [$ j-1] <=$ w) {if (! Isset ($ a [$ j-1] [$ I-$ dx [$ j-1]) continue; // wi + opt (i-1, wi) $ tmp = $ a [$ j-1] [$ I-$ dx [$ j-1] + $ qz [$ j-1]; // opt (i-1, w ), wi + opt (i-1, w-wi) => compare if ($ tmp> $ a [$ j] [$ I]) {$ a [$ j] [$ I] = $ tmp ;}}// print this array, the output rightmost value is for ($ j = 0; $ j <= 4; $ j ++) {for ($ I = 0; $ I <= 15; $ I ++) {echo $ a [$ j] [$ I]. "/t" ;}echo "/n" ;}?>
I hope this article will help you with php programming.