• Algs4-1.3.37Josephus问题


    1.3.37Josephus问题。在这个古老的问题中,N个身陷绝境的人一致同意通过以下方式减少生存人数。他们围坐成一圈(位置记为0到N-1)并从第一个人开始报数,报到M的人会被杀死,直到最后一个人留下来。传说中Josephus找到了不会被杀死的位置。编写一个Queue的用例Josephus,从命令行接受N和M并打印出人们被杀死的顺序(这也将显示Josephus在圈中的位置)。
    % java Josephus 7 2 
    1350426
    答:
    图片
    public class test
    {
       public static void main(String[] args)
       {
          int N=Integer.parseInt(args[0]);
          int M=Integer.parseInt(args[1]);
          boolean[] a=new boolean[N];
          Queue<Integer> q=new Queue<Integer>();
          for(int i=0;i<N;i++)
              a[i]=true;
          //
          int remain=N;
          int i=0;
          int say=0;
          while(remain!=0)
          {
              if(a[i]) say++;
              if(say==M)
              {
                  say=0;
                  a[i]=false;
                  remain--;
                  q.enqueue(i);
              }
              i++;
              if(i==N) i=0;
           }//end while
           for(Integer item:q)
               StdOut.print(item+" ");
       }//end main
      }//end class

  • 相关阅读:
    3. 文件存储格式
    2. Reduce 输出压缩
    Nginx+Tomcat搭建集群环境
    redis缓存失效及解决方案
    几种开源NOSQL数据库
    使用Maven开发用户模块的CRUD(增删改查)
    Spring Boot 面试题整理
    oracle 11g&12c(pdb&cdb)系统巡检
    Redhat 6.8部署oracle12.2.0.1.0
    sqlserver创建程序集
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854318.html
Copyright © 2020-2023  润新知