PHP贪婪算法解决0-1背包问题实例分析

2025-05-29 0 52

本文实例讲述了PHP贪婪算法解决0-1背包问题的方法。分享给大家供大家参考。具体分析如下:

贪心算法解决0-1背包问题,全局最优解通过局部最优解来获得!比动态规划解决背包问题更灵活!

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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背包贪心算法问题

class tanxin{

public $weight;

public $price;

public function __construct($weight=0,$price=0)

{

$this->weight=$weight;

$this->price=$price;

}

}

//生成数据

$n=10;

for($i=1;$i<=$n;$i++){

$weight=rand(1,20);

$price=rand(1,10);

$x[$i]=new tanxin($weight,$price);

}

//输出结果

function display($x)

{

$len=count($x);

foreach($x as $val){

echo $val->weight,' ',$val->price;

echo '<br>';

}

}

//按照价格和重量比排序

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;

}

}

}

}

//贪心算法

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);//显示

echo '0-1背包最优解为:';

echo tanxin($x);

希望本文所述对大家的php程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP贪婪算法解决0-1背包问题实例分析 https://www.kuaiidc.com/101954.html

相关文章

发表评论
暂无评论