【题目】
某大学开学进行军训队列训练,将学生从一开始按顺序依次编号,并排成一行横队,训练的规则如下:从头开始一至二报数,凡报到二的出列剩下的依次向前靠拢,再从头开始进行一至三报数,凡报到三的出列,剩下的依次向前靠拢,继续从头开始进行一至二报数。。。以后每次从头开始轮流进行一至二报数、一至三报数直到剩下的人数不超过三人为止。
输入
第一行为组数N,接着为N行学生人数,学生人数不超过5000。
样例输入
2
20
40
输出
输出有N行,分别对应输入的学生人数,每行输出剩下的学生最初的编号,编号之间有一个空格。
样例输出
1 7 19
1 19 37
时间限制
C/C++语言:1000MS其它语言:3000MS
内存限制
C/C++语言:65536KB其它语言:589824KB
【solution1】
package dynamic_planing;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class ArmyTranining {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int m = sc.nextInt();
check(m);
}
}
static void check(int m){
List<Integer> list = new LinkedList<>();
for (int i = 1; i <= m; i++) {
list.add(i);
}
int i = 0;
while (list.size() > 3){
if(i % 2 == 0){
Iterator it = list.iterator();
int j = 1;
while (it.hasNext()){
int k = (int) it.next();
if(j == 2){
it.remove();
j = 1;
}else{
j++;
}
}
}else{
Iterator it = list.iterator();
int j = 1;
while (it.hasNext()){
int l = (int) it.next();
if(j == 3){
it.remove();
j = 1;
}else{
j++;
}
}
}
i++;
}
int len = list.size();
for (int j = 0; j < len; j++) {
if(j != len - 1){
System.out.print(list.get(j) + " ");
}else{
System.out.println(list.get(j));
}
}
}
}
【solution2】
package dynamic_planing;
import java.util.Scanner;
public class ArmyTranining_method2 {
static int[] record;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int m = sc.nextInt();
check(m);
}
}
static void check(int m){
record = new int[m];
int i = 0;
while (getSize() > 3){
if(i % 2 == 0){
int k = 1;
for (int j = 0,len = record.length; j < len; j++) {
if(record[j] == 0){
if(k == 2){
record[j] = 1;
k = 1;
}else{
k++;
}
}
}
}else{
int k = 1;
for (int j = 0,len = record.length; j < len; j++) {
if(record[j] == 0){
if(k == 3){
record[j] = 1;
k = 1;
}else{
k++;
}
}
}
}
i++;
}
for (int j = 0, len = record.length; j < len; j++) {
if(record[j] == 0){
System.out.print(j+1 + " ");
}
}
System.out.println();
}
static int getSize(){
int sum = 0;
for (int i = 0, len = record.length; i < len; i++) {
if(record[i] == 0){
sum++;
}
}
return sum;
}
}