码迷,mamicode.com
首页 > 其他好文 > 详细

uva 11129 An antiarithmetic permutation (递归)

时间:2015-03-07 15:47:10      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:acm   c语言   uva   

                      uva 11129 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 (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


题目大意:给定一个数n, 求一个0~n-1组成的序列,使得其中同向的升序或降序不为等差数列。

解题思路:利用递归,每次都将奇数序号的数和偶数序号的数分开再合并(放在两边),地轨道最后就是答案。



#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int num[10005], A[10005], B[10005];
void solve(int a, int b) {
	if (a == b) {
		return;
	}
	int temp = a, cnt1 = 0, cnt2 = 0;
	for (int i = a; i <= b; i += 2) {
		A[cnt1++] = num[i];
	}
	for (int i = a + 1; i <= b; i += 2) {
		B[cnt2++] = num[i];
	}
	for (int i = 0; i < cnt1; i++) {
		num[temp++] = A[i];
	}
	for (int i = 0; i < cnt2; i++) {
		num[temp++] = B[i];
	}
	solve(a, a + cnt1 - 1);
	solve(a + cnt1, a + cnt1 + cnt2 - 1);
}
int main() {
	int n;
	while (scanf("%d", &n), n) {
		for (int i = 0; i < n; i++) {
			num[i] = i;
		}
		solve(0, n - 1);
			printf("%d:", n);
		for (int i = 0; i < n; i++) {
			printf(" %d", num[i]);
		}
		printf("\n");
	}
	return 0;
}



uva 11129 An antiarithmetic permutation (递归)

标签:acm   c语言   uva   

原文地址:http://blog.csdn.net/llx523113241/article/details/44116379

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!