PHP Dynamic planning solves 0-1 knapsack problem case Analysis
This article mainly introduces the PHP dynamic planning to solve the 0-1 knapsack problem, the case analysis of knapsack problem principle and implementation skills, the need for friends can refer to the next
In this paper, the dynamic programming of PHP is analyzed to solve 0-1 knapsack problem. Share to everyone 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 item weighs t, and the value of each item is v.
To make the backpack the most weight (but not more than W), but also need the most valuable backpack.
Idea: Define a two-dimensional array, one-dimensional for the number of items (for each item), two-dimensional is the weight (not exceeding the maximum, here is 15), the following array a,
The principle of dynamic programming, Max (OPT (i-1,w), wi+opt (I-1,W-WI)), the maximum value,
Opt (I-1,W-WI) refers to the previous optimal solution
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
This is what I wrote based on the principle of dynamic programming. Max (opt (i-1,w), wi+opt (I-1,W-WI)) The backpack can fit the maximum weight $w = 15; Here 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); Define an array $a =array (); Initialization 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]; Not greater than the largest 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; } } } } To print this array, the value of the right-hand corner of the output is maximum value. for ($j =0; $j <=4; $j + +) { for ($i =0; $i <=15; $i + +) { echo $a [$j] [$i]. " /T "; } echo "/n"; } ?> |
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/973132.html www.bkjia.com true http://www.bkjia.com/PHPjc/973132.html techarticle PHP dynamic planning to solve 0-1 knapsack problem case Analysis This article mainly introduces the PHP dynamic planning to solve the 0-1 knapsack problem, the case analysis of knapsack problem principle and implementation skills, the need for friends can ...