CCF 201712-2 游戏(Java)

问题描述
  有n个小朋友围成一圈玩游戏,小朋友从1至n编号,2号小朋友坐在1号小朋友的顺时针方向,3号小
朋友坐在2号小朋友的顺时针方向,……,1号小朋友坐在n号小朋友的顺时针方向。
  游戏开始,从1号小朋友开始顺时针报数,接下来每个小朋友的报数是上一个小朋友报的数加1。若
一个小朋友报的数为k的倍数或其末位数(即数的个位)为k,则该小朋友被淘汰出局,不再参加以后的
报数。当游戏中只剩下一个小朋友时,该小朋友获胜。
  例如,当n=5, k=2时:
  1号小朋友报数1;
  2号小朋友报数2淘汰;
  3号小朋友报数3;
  4号小朋友报数4淘汰;
  5号小朋友报数5;
  1号小朋友报数6淘汰;
  3号小朋友报数7;
  5号小朋友报数8淘汰;
  3号小朋友获胜。


  给定n和k,请问最后获胜的小朋友编号为多少?
输入格式
  输入一行,包括两个整数n和k,意义如题目所述。
输出格式
  输出一行,包含一个整数,表示获胜的小朋友编号。
样例输入
5 2
样例输出
3
样例输入
7 3
样例输出
4
数据规模和约定

  对于所有评测用例,1 ≤ n ≤ 1000,1 ≤ k ≤ 9。

问题分析

      典型约瑟夫环问题

public class B {
    public class Node{
        int num=0;
        Node next=null;

        Node(int num, Node next){
            this.num=num;
            this.next=next;
        }
    }

    private Node head=null;
    private Node last=null;
    private int length=0;

    private void add(int num){
        Node temp=new Node(num,null);
        if(isEmpty()){
            head=temp;
            last=temp;
            length++;
        }else{
            last.next=temp;
            last=last.next;
            length++;
        }
    }

    private boolean isEmpty() {
        return length==0;
    }

    private Node getResult(int n, int k){
        Node front=null;
        Node now=null;
        for(int i=1;i<=n;i++){
            add(i);
            front=last;
        }
        last.next=head;
        now=head;
        int count=0;
        while(front!=now){
            if(++count!=k){
                front=front.next;
            }else {
                front.next=now.next;
                count=0;
            }
            now=front.next;
        }
        return now;
    }

    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        int n=scan.nextInt();
        int k=scan.nextInt();
        B b=new B();
        System.out.println(b.getResult(n,k).num);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33769788/article/details/79337848