某部队进行新兵队列训练,将新兵从一开始按顺序依次编号,并排成一行横队,训练的规则如下:从头开始一至二报数,凡报到二的出列,剩下的向小序号方向靠拢,再从头开始进行一至三报数,凡报到三的出列,剩下的向小序号方向靠拢,继续从头开始进行一至二报数。。。,以后从头开始轮流进行一至二报数、一至三报数直到剩下的人数不超过三人为止。
Input
本题有多个测试数据组,第一行为组数N,接着为N行新兵人数,新兵人数不超过5000。
Output
共有N行,分别对应输入的新兵人数,每行输出剩下的新兵最初的编号,编号之间有一个空格。
Sample Input
2
20
40
Sample Output
1 7 19
1 19 37
思路
详细见代码
代码
package lanqiaoPractice.stack;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class HDU1276 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int T = Integer.parseInt(in.nextLine());
while (T-- > 0){
int N = Integer.parseInt(in.nextLine());
Queue<Integer> queue = new LinkedList<>();
for(int i = 1; i <= N; i++) queue.add(i);
while (queue.size() > 3){
// add代表是否加入新队列中,每次把报1的士兵加入新队列
boolean add = true;
Queue<Integer> NewQueue = new LinkedList<>();
while (!queue.isEmpty()){
if(add){
NewQueue.add(queue.poll());
}else{
queue.poll();
}
add = !add;
}
// 用新队列替换原队列
queue = NewQueue;
// 如果人数已经不超过3人则退出
if(queue.size() <= 3) break;
// 用count来标记是否加入新队列,当count为2即报3的士兵, 不加入新队列中
NewQueue = new LinkedList<>();
int count = 0;
while (!queue.isEmpty()){
if(count == 2){
queue.poll();
}else{
NewQueue.add(queue.poll());
}
count = (count + 1) % 3;
}
// 用新队列替换原队列
queue = NewQueue;
}
// 打印
for(int i = 0, l = queue.size(); i < l; i++){
System.out.print(queue.poll());
System.out.print(' ');
}
System.out.print('\n');
}
}
}