1.3.37

question:

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 themselves in a circle (at positions numbered from 0 to N-1) and proceed around the circle, eleminating 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 (annd thus would show Josephus where to sit in the circle).

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

answer:

法一://最笨的方法,就是用循环链表来模拟

import edu.princeton.cs.algs4.*;

public class Josephus
{
    private class Node
    {
        int pos;
        Node next;
    }
    
    private Node head = null;
    private Node current = null;
    private int N = 0;
    
    public int size()
    {
        return N;
    }
    
    public void add(int n)
    {
        Node node = new Node();
        node.pos = n;
        node.next = null;
        if(N == 0)
        {
            head = node;
            head.next = head;
            current = head;
            N++;
            return;
        }
        current.next = node;
        node.next = head;
        current = node;
        N++;
    }
    
    public Node remove(Node first, int n)//删除first后的第n个,并返回第n+1个node
    {
        if(N == 1)
        {
            StdOut.println(first.pos);
            return first;
        }
        Node p = first;
        for(int i = 0; i < n-2;i++)
        {
            p = p.next;
        }
        for(int i = 0; i < n-1; i++)
        {
            first = first.next;
        }
        StdOut.print(first.pos + "\t");
        p.next = first.next;
        N--;
        return p.next;//返回删除后的下一个节点
    }
    
    public Node return_head()
    {
        return head;
    }
    
    public static void main(String[] args)
    {
        Josephus josephus = new Josephus();
        StdOut.println("input the N and M:");
        int N, M;
        N = StdIn.readInt();
        M = StdIn.readInt();
        for(int i = 0; i < N; i++)//添加节点
        {
            josephus.add(i);
        }
        Node pos = josephus.return_head();//起始位置
        int n = josephus.size(); 
        
        while(n>=1)
        {
            pos = josephus.remove(pos,M);//删除节点
            n--;
        }
    }
}

//还有用数学公式推导的方法来求,会非常简单

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9075180.html
今日推荐