题目描述:
Kolakoski序列是个自主生成的无限序列。
例如,当给定的整数组为[1, 2]时,Kolakoski序列是这样的:
[1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, ...]
如果我们将相邻的相同的数字分成一组,那么将会得到:
[[1], [2, 2], [1, 1], [2], [1], [2, 2], [1], [2, 2], [1, 1], [2], [1, 1], [2, 2], [1], [2], [1, 1], [2], [1], [2, 2], [1, 1],...]
可以看出,每组数字交替由1, 2组成。
接下来对每个分组求他的长度,得到:
[1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, ...]
可以看出,经过如上的变换后,数列保持不变。
对于其他给定的整数组,同样可以用类似的方法构造Kolakoski序列,例如给定整数组[2, 3]时:
[2, 2, 3, 3, 2, 2, 2, 3, 3, 3, 2, 2, 3, 3, 2, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3, 2, 2, 3, 3,...]
给定整数组[2, 1, 3, 1]时,构造得到如下:
[2, 2, 1, 1, 3, 1, 2, 2, 2, 1, 3, 3, 1, 1, 2, 2, 1, 3, 3, 3, 1, 1, 1, 2, 1, 3, 3, 1, 1,...]
介绍:
import java.util.ArrayList;
import java.util.Scanner;
public class MainOne {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int[] a=new int[m];
for (int i = 0; i < a.length; i++) {
int next=sc.nextInt();
a[i]=next;
}
ArrayList<Integer> list=new ArrayList<Integer>();
for (int i = 0; i < a[0]; i++) {
list.add(a[0]);
}
int count=1;
if (list.size()==1) {
for (int i = 0; i < a[1]; i++) {
list.add(a[i]);
}
count=2;
}
while (list.size()<n) {
int time=list.get(count);
for (int i = 0; i < time; i++) {
list.add(a[count%m]);
}
count++;
}
for (int i = 0; i < n; i++) {
System.out.println(list.get(i));
}
}
}
输入:
30 4
2 1 3 1
输出:
2 2 1 1 3 1 2 2 2 1 3 3 1 1 2 2 1 3 3 3 1 1 1 2 1 3 3 1 1 2