您的位置:首页 > 其它

An antiarithmetic permutation +uva+分治

2014-07-18 20:38 239 查看

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

解决方案:可将1.......n-1。中的偶数位置的数放到前半段,奇数位置的数放到后半段,然后对前半段如此,后半段也如此,不断继续下去,之后就形成的没有三个的等差数列。这方法我怎么没想到,,,,,。可用分治法实现。

代码:
#include<iostream>
#include<cstdio>
#define MMAX 10003
using namespace std;
int n;
int a[MMAX];
int t[MMAX];
void solve(int L,int R){
if(L+1>=R) return ;
int j=0;
for(int i=L;i<=R;i++){
t[i]=a[i];
}
j=L;
for(int i=L;i<=R;i+=2){
a[j++]=t[i];
}
for(int i=L+1;i<=R;i+=2){
a[j++]=t[i];
}

int mid=(L+R)/2;
solve(L,mid);solve(mid+1,R);
}
int main(){
while(~scanf("%d",&n)&&n){
for(int i=0;i<n;i++){
a[i]=i;
}
solve(0,n-1);
printf("%d:",n);
for(int i=0;i<n;i++){
printf(" %d",a[i]);

}

cout<<endl;
}
return 0;}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: