1. 程式人生 > >演算法競賽入門-救濟金髮放(The Dole Queue )

演算法競賽入門-救濟金髮放(The Dole Queue )

1、題目

n(n<20)個人站成一圈,逆時針編號為1~n。有兩個官員,A從1開始逆時針數,B從n開始順時針數。在每一輪中,官員A數k個就停下來,官員B數m個就停下來(注意有可能兩個官員停在同一個人上)。接下來被官員選中的人(1個或者2個)離開隊伍。

輸入n,k,m輸出每輪裡被選中的人的編號(如果有兩個人,先輸出被A選中的)。例如,n=10,k=4,m=3,輸出為4 8, 9 5, 3 1, 2 6, 10, 7。注意:輸出的每個數應當恰好佔3列。

輸入: 
10 4 3

輸出: 
_ _ 4_ _ 8,_ _ 9_ _ 5,_ _ 3_ _ 1,_ _ 2_ _ 6,_ 10,_ _ 7

2、思路

 思路:用陣列儲存資料,然後出佇列的資料標記為1,再次進行迴圈的時候判斷當前的下標是否訪問

3、程式碼

package basic.第四章;

import java.util.Scanner;

/**
 * Created by Administrator on 2018/6/7.
 * 思路:用陣列儲存資料,然後出佇列的資料標記為1,再次進行迴圈的時候判斷當前的下標是否訪問
 *
 * @author 春風吹又生
 */
public class DoleQueue {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);

        //------輸入資料-----
        int n = read.nextInt();
        int k = read.nextInt();
        int m = read.nextInt();


        //-----初始化陣列
        int[] arr = new int[n + 1];

        arr[0] = -1;
        //------迴圈出佇列----
        int front = 0;
        int rear = n + 1;
        int total = n;
        // 如果當前的人數沒有出完
        while (total != 0) {
            // 從A開始
            front = out(front, arr, k, 1, n);
            // 從B開始
            rear = out(rear, arr, m, -1, n);
            //  當前出佇列的資料
            arr[front % (n + 1)] = 1; // 標記當前出佇列的人
            arr[rear % (n + 1)] = 1;
            System.out.printf("%3d", front % (n + 1));
            total--;
            if (front % (n + 1) != rear % (n + 1)) {// 如果頭尾不相逢
                System.out.printf("%3d", rear % (n + 1));
                total--;
            }
            if(total!=0){
                System.out.printf(",");
            }
        }
    }

    /**
     * @param direction 方向 頭或者尾開始的下標
     * @param arr       陣列
     * @param step      步數
     * @param every     每一步
     */
    private static int out(int direction, int[] arr, int step, int every, int total) {
        //-------只要找到一個,則退出---------
        int temp = 0;
        while (temp != step) {
            if (arr[(direction + every) % (total + 1)] == 0) {
                temp++;
                direction += every;

                // 如果達到尾
                if (direction == total + 1) {
                    direction = 1;
                }
                // 如果到達頭
                else if (direction == 0) {
                    direction = total + 1;
                }
            } else {
                direction += every;
                if (direction == 0) {
                    direction = total + 1;
                }
            }
        }

        return direction;
    }
}