PHP Dynamic Programming Solution 0-1 knapsack Problem Example Analysis _php skill

Source: Internet
Author: User

This article analyzes the dynamic programming of PHP to solve 0-1 knapsack problem. Share to everyone for your reference. The specific analysis is as follows:

Knapsack problem Description: A backpack that bears the maximum weight of W, now has n items, each item weighs t, and the value of each item is v.
To make this backpack the most weight (but not more than W), but also need the most valuable backpack.

Train of thought: Define a two-dimensional array, one dimension for the item quantity (expression 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) means the last optimal solution

<?php
//This is I write according to the dynamic programming principle
//MAX (opt (i-1,w), wi+opt (I-1,W-WI))
//backpack can be loaded with 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);
Defines an array
$a =array ();
Initialize 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];
    is not greater than the maximum 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) => to compare 
      if ($tmp > $a [$j] [$i]) {
        $a [$j] [$i]= $tmp;
      }
}}}
//Print this array, the value of the output is the 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 will help you with your PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.