uva 11129 - An antiarithmetic permutation

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 (pipjpk) 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

W. Guzicki, adapted by P. Rudnicki

用0到n-1 构造一个无等差子序列的序列。分治法,如何要确保划分出来的,左右两边的不会构成等差数列呢?把当前序列奇数位置的数划分到左边,偶数位置的数划分到右边。

import java.util.ArrayList;
import java.util.Scanner;


public class Main {
	public final static int maxn = 10000 + 5;
	
	public static int[] a = new int[maxn];
	
	public static void solve(int x, int y){
		if(y-x <= 1) return;
		ArrayList<Integer> temaArrayList = new ArrayList<>();
		ArrayList<Integer> tembArrayList = new ArrayList<>();
		for(int i = x;i <= y;i+=2){
			temaArrayList.add(a[i]);
		}
		for(int i = x+1;i <= y;i+=2){
			tembArrayList.add(a[i]);
		}
		for(int i = 0;i < temaArrayList.size();i++){
			a[x+i] = temaArrayList.get(i);
		}
		solve(x, x+temaArrayList.size()-1);
		for(int i = 0;i < tembArrayList.size();i++){
			a[x+temaArrayList.size()+i] = tembArrayList.get(i);
		}
		solve(x+temaArrayList.size(), y);
	}
	
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(true){
			int n = scanner.nextInt();
			for(int i = 0;i < n;i++) a[i] = i;
			if(n == 0) break;
			solve(0, n-1);
			System.out.printf("%d:", n);
			for(int i = 0;i < n;i++){
				System.out.printf(" %d", a[i]);
			}
			System.out.println();
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值