PHP greedy algorithm solves 0-1 knapsack problem case Analysis
This article mainly introduces the PHP greedy algorithm solves 0-1 knapsack problem, the example analyzes the greedy algorithm principle and the knapsack problem realization skill, needs the friend to refer to the next
This article describes the PHP greedy algorithm to solve the 0-1 knapsack problem method. Share to everyone for your reference. The specific analysis is as follows:
Greedy algorithm solves 0-1 knapsack problem, the global optimal solution is obtained by local optimal solution! More flexible than dynamic planning to solve knapsack problems!
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 |
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 results
function display ($x)
{
$len =count ($x);
foreach ($x as $val) {
echo $val->weight, ", $val->price;
Echo '
';
}
}
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-ascending order
Display ($x);//Show
The best solution for Echo ' 0-1 backpack is: ';
echo tanxin ($x);
|
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/973134.html www.bkjia.com true http://www.bkjia.com/PHPjc/973134.html techarticle PHP greedy algorithm solves 0-1 knapsack problem case analysis This article mainly introduced the PHP greedy algorithm solves 0-1 knapsack problem, the example analyses the greedy algorithm principle and the knapsack problem realization skill, needs ...