Home > Backend Development > PHP Tutorial > 约瑟夫环有关问题的链表解法和数学解法(PHP)

约瑟夫环有关问题的链表解法和数学解法(PHP)

WBOY
Release: 2016-06-13 12:23:06
Original
1128 people have browsed it

约瑟夫环问题的链表解法和数学解法(PHP)

约瑟夫环问题

一群猴子排成一圈,按1,2,…,n依次编号。然后从第1只开始数,数到第m只,把它踢出圈,从它后面再开始数,再数到第m只,在把它踢出去…,如此不停的进行下去,直到最后只剩下一只猴子为止,那只猴子就叫做大王。要求编程模拟此过程,输入m、n,输出最后那个大王的编号。

链表解法

<code>function king($n,$m){    $monky = range(1,$n);    $i = 0;    while(count($monky)>1){        $i+=1;        $head = array_shift($monky);        if($i%$m!=0){            array_push($monky,$head);        }    }    return $monky[0];}echo king(10,3);</code>
Copy after login

数学解法

  • x’ = 2 3 4 5 0
  • x = 0 1 2 3 4
  • x’ = (x+m)%n

    <code>function king2($n,$m){    $r = 0;    for($i=2;$i</code>
    Copy after login

版权声明:本文为博主原创文章,未经博主允许不得转载。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template