题目内容:
Arithmetic Progression
“Inmathematics, an arithmetic progression (AP) or arithmetic sequence is asequence of numbers such that the difference between the consecutive terms isconstant. For instance, the sequence 5, 7, 9, 11, 13, … is an arithmeticprogression with common difference of 2.”
- Wikipedia
Thisis a quite simple problem, give you the sequence, you are supposed to find thelength of the longest consecutive subsequence which is an arithmeticprogression.
Input
Thereare several test cases. For each case there are two lines. The first linecontains an integer number N (1 <= N <= 100000) indicating the number ofthe sequence. The following line describes the N integer numbers indicating thesequence, each number will fit in a 32bit signed integer.
Output
Foreach case, please output the answer in one line.
Sample Input
1 4 7 9 11 14
Sample Output
3
题目大意:
输入的第一行为一个数N。接下来一行输入N个数,输出为这N个数中最大的等差数列的个数。
解题思路:
解决这个问题,主要是用一个数组来储存着N个数,然后根据等差数列的公差相等来相互比较相邻几个数是否为等差数列,主要是利用两个循环来解决个问题,同时用len来记录等差数列的长度。因为本题数据较大,宜采用C语言来编写,可以节约运算时间。
解题代码:
#include<stdio.h>
int main()
{
int N;
while(scanf("%d",&N)!=EOF) //输入
{
int a[100005];
int i,j;
for(i=0;i<N;i++){
scanf("%d",&a[i]);
}
int d,s=0,t;
int ans=1;
while(s<N-1)
{
t=s+1;
d=a[t]-a[s];
while(t<N && a[t]-a[t-1]==d)t++; //满足等差数列,t 自加,t为最后一个等差数列的数的下表
t--; //不满足等差数列的时候,t 自减一次,也就是向后退一步
if(ans<t-s+1) //比较数列的大小
{
ans=t-s+1;
}
s=t;
}
printf("%d\n",ans); //输出结果
}
return 0;
}
解题感想:
这道题目属于较简单的题目,主要来练习对于数组的掌握情况,熟练掌握数组的规律,知道等差数列的公差相等,接着道题目应该不难,最主要在于时间的消耗,对于数据较大的题目,易采用C语言来编写,可以解决程序运行的时间,如果数据不大,或者对时间要求较低,则经可能采用C++语言来编写比较方便。