PHP backtracking solves the problem of 0-1 backpacking instances and analyzes 0-1 instances. The PHP backtracking method solves the problem of 0-1 backpacks. the example in this article describes the PHP backtracking method to solve the problem of 0-1 backpacks. Share it with you for your reference. The specific analysis is as follows: the PHP backtracking method solves the 0-1 knapsack problem instance analysis, and the 0-1 instance analysis
This article describes how PHP backtracking solves the problem of 0-1 backpacks. Share it with you for your reference. The specific analysis is as follows:
This code is written according to the pseudocode in the software designer tutorial;
The most troublesome thing is not to change the pseudo code to php, but to judge the array subscript starting from 0 and the corresponding subscript;
Write it with debugging output
<? Php $ v_arr = array (, 33,); $ w_arr = array (, 43,); $ n = count ($ w_arr ); // test output var_dump (bknap1 (110); // var_dump (bound (139,89, 7,110); function bound ($ v, $ w, $ k, $ W_total) {global $ v_arr, $ w_arr, $ n; $ B = $ v; $ c = $ w; // var_dump ($ W_total); var_dump ($ n ); var_dump ($ k); var_dump ($ v); var_dump ($ w); // die; for ($ I = $ k + 1; $ I <$ n; $ I ++) {$ c = $ c + $ w_arr [$ I]; // var_dump ($ W_total); var_dump ($ C); if ($ c <$ W_total) $ B + = $ v_arr [$ I]; else {// var_dump (1-($ c-$ W_total) /$ w_arr [$ I]) * $ v_arr [$ I]); $ B = $ B + (1-($ c-$ W_total) /$ w_arr [$ I]) * $ v_arr [$ I]; return $ B;}/* var_dump ('------ bound head'); var_dump ($ k ); var_dump ($ B); var_dump ('------ bound end'); */return $ B;} function bknap1 ($ W_total) {global $ v_arr, $ w_arr, $ n; $ cw = $ cp = 0; $ k = 0; $ fp =-1; while (true) {while ($ k <$ n & $ cw + $ w_arr [$ k] <= $ W_to Tal) {$ cw + = $ w_arr [$ k]; $ cp + = $ v_arr [$ k]; $ Y_arr [$ k] = 1; $ k + = 1;} // var_dump ($ cw); var_dump ($ cp); var_dump ($ Y_arr); var_dump ($ k); var_dump ($ n ); if ($ k = $ n) {$ fp = $ cp; $ fw = $ cw; $ k = $ n-1; $ X_arr = $ Y_arr; // bound ($ cp, $ cw, $ k, $ W_total); // var_dump (bound ($ cp, $ cw, $ k, $ W_total), $ fp, $ k); die; // var_dump ($ fp); var_dump ($ fw); var_dump ($ Y_arr); var_dump ($ k); var_dump ($ n );} else {$ Y_arr [$ k] = 0;} // var_dump ($ Y_arr ); Var_dump ($ k); var_dump ($ n); // die; // var_dump (bound ($ cp, $ cw, $ k, $ W_total), $ fp ); die; while (bound ($ cp, $ cw, $ k, $ W_total) <= $ fp) {while ($ k> = 0 & $ Y_arr [$ k]! = 1) {$ k-= 1;} if ($ k <0) {return $ X_arr;} var_dump ($ k); $ Y_arr [$ k] = 0; $ cw-= $ w_arr [$ k]; $ cp-= $ v_arr [$ k];} $ k + = 1 ;}}?>
I hope this article will help you with php programming.
Examples in this article describe the PHP backtracking method to solve the problem of 0-1 backpacks. Share it with you for your reference. The specific analysis is as follows :...