Php greedy algorithm 0-1 backpack problem
1. [Code]Hope experts can use other algorithms to implement the 0-1 backpack
// Class tanxin {public $ weight; public $ price; public function _ construct ($ weight = 0, $ price = 0) {$ this-> weight = $ weight; $ this-> price = $ price ;}// generate data $ n = 10; for ($ I = 1; $ I <= $ n; $ I ++) {$ weight = rand (); $ price = rand ); $ x [$ I] = new tanxin ($ weight, $ price);} // output result function display ($ x) {$ len = count ($ x ); foreach ($ x as $ val) {echo $ val-> weight, '', $ val-> price; echo'
';}} // Sort the function tsort (& $ x) {$ len = count ($ x); for ($ I = 1; $ I <= $ len; $ I ++) {for ($ j = 1; $ j <= $ len-$ I; $ j ++) {$ temp = $ x [$ j]; $ res = $ x [$ j + 1]-> price/$ x [$ j + 1]-> weight; $ temres = $ temp-> price/$ temp-> weight; if ($ res> $ temres) {$ x [$ j] = $ x [$ j + 1]; $ x [$ j + 1] = $ temp ;}}// greedy algorithm function tanxin ($ x, $ totalweight = 50) {$ len = count ($ x); $ allprice = 0; for ($ I = 1; $ I <= $ len; $ I ++) {if ($ x [$ I]-> weight> $ totalweight) break; else {$ allprice + = $ x [$ I]-> price; $ totalweight = $ totalweight-$ x [$ I]-> weight;} if ($ I <$ len) $ allprice + = $ x [$ I]-> price * ($ totalweight/$ x [$ I]-> weight); return $ allprice;} tsort ($ x ); // display ($ x) by non-incrementing order; // The echo '0-1 backpack's optimal solution is: '; echo tanxin ($ x );