201712-2 游戏 Java

思路:
第一感觉有点像约瑟夫环。想到用队列解决比较好理解

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        Queue<Integer> children = new LinkedList<Integer>();
        for(int i=1;i<=n;i++) {
            children.offer(i);
        }
        for(int j=1;children.size()!=1;j++) {
            int temp = children.poll();//每个数都出队
            if(!(j%k==0 || j%10==k)) {//如果不出局就再入队
                children.offer(temp);
            }
        }
        sc.close();
        System.out.println(children.poll());
    }

}

普通队列:
LinkedList支持队列的行为,并且实现了Queue接口,上转型为Queue。
add和offer都是将一个元素插入到队尾。offer方法不会返回null,add会返回null
peak和element在不移除的情况下返回队头。peak会返回null
poll和remove将移除并返回队头。poll会返回null

此外还有优先级队列,双端队列可以学习,了解一下。

猜你喜欢

转载自www.cnblogs.com/yu-jiawei/p/12370939.html