题目:http://codevs.cn/problem/1006/
题解:
/* 1006 等差数列 */
#include <stdio.h>
#define DEBUG
#define MAXSIZE 100
int n; /* 数据大小 */
int array[MAXSIZE]; /* 所有数值 */
int maxcount; /* 最大计数 */
int darray[MAXSIZE]; /* 差值数组 */
/* 交换数组位置 */
void swap(int a, int b){
int tmp;
tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
/* 按值顺序排列数组 */
void sort(int s){
int i, j;
for(i = 0; i < s; i++){
for(j = i + 1; j < s; j++){
if(array[i] > array[j]){
swap(i, j);
}
}
}
}
/* 判断数值是否存在于样本中, 存在返回位置,否则返回0 */
int in_array(int start, int x){
int i;
for(i = start; i < n; i++){
if(x < array[i]){
return 0;
}
if(x == array[i]){
return i;
}
}
return 0;
}
/* 依次遍历数组 */
void get_darray(int start){
int i, di;
int count;
int an;
int fi;
di = 0;
/* 获取所有可能的差值 */
for(i = start + 1; i < n; i++){
if(array[i] > array[start]){
darray[di] = array[i] - array[start];
di++;
}
}
/* 遍历样本,获取最长的等差数列 */
for(i = 0; i < di; i++){
fi = start + 1;
count = 1;
for(an = array[start] + darray[i]; an <= array[n - 1]; an = an + darray[i]){
if((fi = in_array(fi, an)) > 0){
count = count + 1;
}
else{
break;
}
}
maxcount = (count > maxcount) ? count : maxcount;
}
}
/* 主函数入口 */
int main(int argc, char *argv[]) {
int i;
#ifdef DEBUG
FILE *fp;
if(NULL == (fp = fopen("data.txt", "r"))){
return 1;
}
#endif
/* 获取数据样本大小 */
#ifdef DEBUG
fscanf(fp, "%d", &n);
#else
scanf("%d", &n);
#endif
/* 获取数据样本 */
for(i = 0; i < n; i++){
#ifdef DEBUG
fscanf(fp, "%d", &array[i]);
#else
scanf("%d", &array[i]);
#endif
}
/* 排序数据样本 */
sort(n);
/* 设置最长等差数列初值 */
maxcount = 1;
/* 依次获取所有可能的等差数列 */
for(i = 0; i < n - 1; i++)
get_darray(i);
printf("%d", maxcount);
#ifdef DEBUG
fclose(fp);
#endif
return 0;
}