约瑟夫环问题--java

来源:互联网 发布:论文投稿代理 知乎 编辑:程序博客网 时间:2024/04/28 12:48

有编号从1到N的N个人坐成一圈报数,报到M的人出局,下一位再从1开始,
 如此持续,直止剩下一位为止,报告此人的编号X。输入N,M,求出X。


那么问题就是,对于n个人,最后剩下的是谁呢?
对于5个人的情况是这样地:
1,2,3,4,5
依此杀掉2,4,1,5
最后剩下的是3

本题参考了zcsunt的程序

/*
 * @(#)Josephus.java
 *
 *
 * 
@author chenyi
 
*/
import java.lang.*;
import java.io.*;

class Node
{
    
 int _data;
    
 Node _next;
    
//------------------------------
    public Node(int d){
        _data 
= d;
    }
  

    public int data(){
        
return _data;
    }
}

class CirLinkList
{
    
 Node _cur;
    in
t _size = 0;
   

    public CirLinkList(int n){
        Node tail 
= new Node(n);
        _cur 
= tail;  
        
for(int i=n-1; i>0; i--){
            Node tmp 
= new Node(i);
            tmp._next 
= _cur;
            _cur 
= tmp;
        }
        tail._next 
= _cur;
        _size 
+= n;
    }
   

    public int size(){
        
return _size;
    }


    public void step(int n){
        
for(int i=0; i<n; i++){
            _cur 
= _cur._next;
        }    
    }
    

    public Node delete(){
        Node temp 
= _cur._next;
        _cur._next 
= temp._next;
        _size
--;
        
return temp;
    }
    

    public void display(){
        Node start 
= _cur, end = _cur;
        
while(end._next != start){
            System.out.print(end._data 
+ " ");
            end 
= end._next;
        }
        System.out.println(end._data );
    }
}


public class Josephus {

    
public static void main(String[] args) throws IOException {
        
        System.out.print(
"Please input the amount of people:");
        String str 
= getString();
        Integer n 
= Integer.parseInt(str);
        CirLinkList L 
= new CirLinkList(n);
        
        System.out.print(
"Please input starting point:");
        String start_position 
= getString();
        Integer start 
= Integer.parseInt(start_position);
        L.step(start
-1);
        
        System.out.print(
"Please input step length:");
        String step_length 
= getString();
        Integer stp 
= Integer.parseInt(step_length);
        
        
while( L.size()>1 ){
            L.step(stp
-2);
            Node death 
= L.delete();
            L.step(
1);
            System.out.println("Now No. " + death.data() 
+ "person leaves");
        }
        //System.out.println(
"");
        System.out.print(
"The survival is:");
        L.display();
    }
    
//---------------------------------------------
    public static String getString() throws IOException{
        InputStreamReader isr 
= new InputStreamReader(System.in);
        BufferedReader br 
= new BufferedReader(isr);
        String s 
= br.readLine();
        
return s;
    }
}
 

原创粉丝点击