<? Php // This is based on the dynamic planning principle. // Max (opt (I-1, w), wi + opt (I-1, w-wi )) // The maximum weight of a backpack $ W = 15; // There are four items, the weight of each item $ Dx = array (3, 4, 5, 6 ); // 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]; // 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) => comparison If ($ tmp> $ a [$ j] [$ I]) { $ A [$ j] [$ I] = $ tmp; } } } } // Print this array and output the rightmost value. For ($ j = 0; $ j <= 4; $ j ++ ){ For ($ I = 0; $ I <= 15; $ I ++ ){ Echo $ a [$ j] [$ I]. "/t "; } Echo "/n "; } ?> |