算法练习(43): 约瑟夫问题(1.3.37)

本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论

算法(第4版)

知识点

  • 约瑟夫问题

题目

1.3.37 Josephus 问题。在这个古老的问题中,N 个身陷绝境的人一致同意通过以下方式减少生存人数。他们围坐成一圈(位置记作 0 到 N-1)并从第一个人开始报数,报到 M 的人会被杀死,直到最后一个人留下来。传说中 Josephus 找到了不会被杀死的位置。编写一个 Queue 的用例 Josephus,从命令行接受 N 和 M 并打印出人们被杀死的顺序(这也将显示 Josephus 在圈中的位置)。


1.3.37 Josephus problem. In the Josephus problem from antiquity, N people are in dire straits and agree to the following strategy to reduce the population. They arrange them- selves in a circle (at positions numbered from 0 to N–1) and proceed around the circle, eliminating every Mth person until only one person is left. Legend has it that Josephus figured out where to sit to avoid being eliminated. Write a Queue client Josephus that takes N and M from the command line and prints out the order in which people are eliminated (and thus would show Josephus where to sit in the circle).

% java Josephus 7 2 
1 3 5 0 4 2 6

分析

本人所有简书的算法文章详细分析已经移入小专栏:算法四习题详解,欢迎大家订阅

f[1]=0;
f[i]=(f[i-1]+m)%i; (i>1)

答案

public class Josephus {

    public static void main(String[] args) {

        int m = 3;
        int N = 41;

        Queue<Integer> queue = new Queue<Integer>();
        for (int i = 0; i < N; i++)
            queue.enqueue(i);

        while (!queue.isEmpty()) {
            for (int i = 0; i < m - 1; i++)
                queue.enqueue(queue.dequeue());
            StdOut.print(queue.dequeue() + " ");
        }
        
        StdOut.println();
    }
}

打印的结果为:
2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36 40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 34 15 30
因此,第31个人是最后一个被杀死的,第16个人是倒数第二个被杀死的

代码索引

Josephus.java

视频讲解

广告

我的首款个人开发的APP壁纸宝贝上线了,欢迎大家下载。

壁纸宝贝

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,934评论 0 23
  • 这是每个人一生中都要经历的过程,然而自己真的到了这个阶段,却又觉得好多事应接不暇,做起来力不从心。人到中年真的经历...
    心灵的旋律阅读 189评论 0 0
  • 当你对一身边的一切都以积极乐观的心态去对待,这是你会发现这种心态可以产生巨大的能量!善于发现生活中的小确幸,寻找或...
    crystalplane一一阅读 591评论 0 0
  • 国庆长假女儿安排到莫干山游玩,两个女儿每家三口带着我们老两口共八人一起在莫干山住了三个晚上。 10月2日下午2点半...
    米老爹阅读 3,691评论 55 56