2014-07-27 14:13:29

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 permutation p 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 (pipjpk) forms an arithmetic progression.

Uva--11129(分治,数学)

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 nfrom 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

思路:分治思想,每次把奇数位置和偶数位置的数分开来,最后出现的排列就可以实现提述要求。
 1 /*************************************************************************
 2     > File Name: l.cpp
 3     > Author: Nature
 4     > Mail: 564374850@qq.com
 5     > Created Time: Sat 26 Jul 2014 12:58:48 PM CST
 6 ************************************************************************/
 7 
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cstdlib>
11 #include <cmath>
12 #include <iostream>
13 #include <algorithm>
14 using namespace std;
15 
16 int n,v[10005],pos;
17 
18 void Work(int p,int cnt,int d){
19     if(cnt == 1){
20         v[pos++] = p;
21         return;
22     }
23     int n1 = ceil(1.0 * cnt / 2);
24     int n2 = cnt / 2;
25     Work(p,n1,2 * d);
26     Work(p + d,n2,2 * d);
27 }
28 
29 int main(){
30     while(scanf("%d",&n) == 1 && n){
31         pos = 0;
32         Work(0,n,1);
33         printf("%d:",n);
34         for(int i = 0; i < n; ++i)
35             printf(" %d",v[i]);
36         printf("\n");
37     }
38     return 0;
39 }

 

 

相关文章: