|
// 0-1 knapsack greedy algorithm Problem
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 (1, 20 );
$ Price = rand (1, 10 );
$ X [$ I] = new tanxin ($ weight, $ price );
}
// Output result
Function display ($ x)
{
$ Len = count ($ x );
Foreach ($ x as $ val ){
Echo $ val-> weight, '', $ val-> price;
Echo '<br> ';
}
}
// Sort by price and weight ratio
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); // sort by non-incrementing order
Display ($ x); // display
Echo '0-1 the optimal solution of the backpack is :';
Echo tanxin ($ x );
|