• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
php算法之约瑟夫问题
<?php
header("Content-type: text/html; charset=utf-8");
/**
 *
 * n个小孩围坐一起.从第m个小孩从1开始数数.数到k的小孩出局.下一个小孩子从1开始数.问最终小孩出列的顺序.
 */
class Person
{
 //编号
 public $no;
 //指向下一个链表的引用
 public $next;
public function __construct($no)
 {
 $this->no = $no;
}
}
//创建环形链表
/**
 * @desc
 * @throws 注意:无DB异常处理
 * @param $n
 * @param $first
 * @return void
 */
function add_person($n,&$first)
{
 for($i=0;$i<$n;$i++){
 $child = new Person($i+1);
 if($i==0){
 //定义第一个链表
 $first=$child;
 //代表本身的链表
 $cur=$child;
 $cur->next=$cur;
 }else{
 $cur->next=$child;
 $child->next=$first;
 $cur=$cur->next;
 }
 }
}
//显示所有的链表
function show_child($first){
 $cur=$first;
 while($cur->next !== $first){
 echo '编号'.$cur->no.'<br/>';
 $cur=$cur->next;
 }
 echo '编号'.$cur->no.'<br/>';
}
/**
 * @desc 环形链表解决约瑟夫问题
 * @throws 注意:无DB异常处理
 * @param $first 第一个链表
 * @param $m 从第几个人开始数
 * @param int $k 哪个数
 * @return void
 */
function count_child($first,$m,$k=1){
 $cur=$first;
 $tail=$first;
 for($i=0;$i<$m-1;$i++){
 $cur=$tail;
 $tail=$tail->next;
 }
 $j=0;
 while($tail != $tail->next){
 if($j==$k-1){
 echo "<br/>出列编号:".$tail->no.'<br/>';
 //踢掉符号条件的链表
 $cur->next=$tail->next;
 //移动当前链表
 $tail=$tail->next;
 $j=0;
 }else{
 //记住上一个链表的位置
 $cur=$tail;
 //移动当前链表
 $tail=$tail->next;
 $j++;
 }
 }
 echo '最后'.$tail->no.'<br/>';
}
add_person(3,$first);
count_child($first,1,2);
//约瑟夫另一种解法
/**
 * @desc 约瑟夫另一种解法
 * @throws 注意:无DB异常处理
 * @param $n 多少个
 * @param $m 哪个数
 * @return int
 */
function yuesefu($n,$m) {
 $r=0;
 for($i=2; $i<=$n; $i++) {
 $r=($r+$m)%$i;
 }
 return $r+1;
}
echo "最后是".yuesefu(5,3);
 //show_child($first);
?>

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/8681353.html

posted on 2018-03-31 11:07  孙龙-程序员  阅读(117)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3