CentOS minimal 上安装 VirtualBox 虚拟机自启动

Problem D: Antiarithmetic?

A permutation of n is a bijective function of the initial n natural numbers: 0, 1, ... n-1. 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 as its first, fifth and sixth term (0, 1, 2) form an arithmetic progression; and so do its second, forth and fifth term (5, 3, 1).

Your task is to check whether a given permutation of n is antiarithmetic.

There are several test cases, followed by a line containing 0. Each test case is a line of the input file containing a natural number 3 ≤ n ≤ 10000 followed by a colon and then followed by n distinct numbers separated by whitespace. All n numbers are natural numbers smaller than n.

For each test case output one line with yes or no stating whether the permutation is antiarithmetic or not.

Sample input

3: 0 2 1 
5: 2 0 1 3 4
6: 2 4 3 5 0 1
0

Output for sample input

yes
no
yes

题意:问是否存在长度3及以上的等差子序列。是输出no,否yes

思路:1、技巧性枚举,先预处理保存每个数字的位置,然后枚举等差中项和等差前项。计算出等差后项。判断位置符不符合即可。

复杂度看似O(n^2),实际上j需要枚举的次数并没有那么多。因为当r>=n的时候就循环结束。

代码:

#include <stdio.h>
#include <string.h>

const int N = 10005;
int n, num[N];

void init() {
	int Num;
	for (int i = 0; i < n; i++) {
		scanf("%d", &Num);
		num[Num] = i;
	}
}

bool judge() {
	for (int i = 0; i < n; i++)
		for (int j = i - 1; j >= 0; j++) {
			if (num[j] > num[i]) continue;
			int r = i * 2 - j;
			if (r >= n) break;
			if (num[r] > num[i])
				return false;
		}
	return true;
}

void solve() {
	if (judge()) printf("yes\n");
	else printf("no\n");
}

int main() {
	while (~scanf("%d%*c", &n) && n) {
		init();
		solve();
	}
	return 0;
}


CentOS minimal 上安装 VirtualBox 虚拟机自启动

上一篇:Linux 工程师技术 <<系统&服务管理进阶>>


下一篇:怎样输出可重集的全排列