Problem A: An antiarithmetic permutation
A permutation of n+1 is a bijective function of the initial n+1 natural numbers: 0, 1, ... n. A permutationp is called antiarithmetic if there is no subsequence of it forming an arithmetic progression of length bigger than 2, i.e. there are no three indices 0 ≤ i < j < k < n such that (pi, pj, pk) forms an arithmetic progression.
For example, the sequence (2, 0, 1, 4, 3) is an antiarithmetic permutation of 5. The sequence (0, 5, 4, 3, 1, 2) is not an antiarithmetic permutation of 6 as its first, fifth and sixth term (0, 1, 2) form an arithmetic progression; and so do its second, fourth and fifth term (5, 3, 1).
Your task is to generate an antiarithmetic permutation of n.
Each line of the input file contains a natural number 3 ≤ n ≤ 10000. The last line of input contains 0 marking the end of input. For each n from input, produce one line of output containing an (any will do) antiarithmetic permutation of n in the format shown below.
Sample input
3 5 6 0
Output for sample input
3: 0 2 1 5: 2 0 1 4 3 6: 2 4 3 5 0 1
①将数组分成奇数位和偶数位两个数组
②分别拿这两个数组重复①步骤
③一直递归直到数组内元素的数量小于3
④最后将数组合并起来便得到题目要求的数组
#include<stdio.h>
int temp1[10010],temp2[10010];
int len1,len2;
int num[10010];
void change(int l,int r){
if(r-l<2)
return;
int i,j;
for(i=l,len1=0;i<=r;i=i+2,len1++){
temp1[len1]=num[i];
}
for(i=l+1,len2=0;i<=r;i=i+2,len2++){
temp2[len2]=num[i];
}
for(i=l,j=0;j<len1;++j,++i){
num[i]=temp1[j];
}
for(j=0;j<len2;++j,++i){
num[i]=temp2[j];
}
int mid=((r-l+1)%2==0?(r-l+1)/2+l-1:(r-l+1)/2+l);
change(l,mid);
change(mid+1,r);
}
int main(){
int n;
int i;
while(scanf("%d",&n)!=EOF){
if(n==0)break;
for(i=0;i<n;++i){
num[i]=i;
}
change(0,n-1);
printf("%d:",n);
for(i=0;i<n;++i){
printf(" %d",num[i]);
}
printf("\n");
}
return 0;
}