题目摘要:“In mathematics, an arithmeticprogression (AP) or arithmetic sequence is a sequence of numbers such that thedifference between the consecutive terms is constant. For instance, thesequence 5, 7, 9, 11, 13, … is an arithmetic progression with common differenceof 2.”
--Wikipedia
This is a quite simple problem, give youthe sequence, you are supposed to find the length of the longest consecutivesubsequence which is an arithmetic progression.
题目大意:给一串数字,算出其中最长等差数列的长度
输入输出要求:
Input
There are several test cases. For each casethere are two lines. The first line contains an integer number N (1 <= N<= 100000) indicating the number of the sequence. The following line describesthe N integer numbers indicating the sequence, each number will fit in a 32bitsigned integer.
Output
For each case, please output the answer inone line.
输入输出样例:
Sample Input
6
1 4 7 9 11 14
Sample Output
3
解题思路:以ans记录最终结果,d为公差,将数组元素一一枚举,l随着d的相等而增加,然后处理其他细节问题即可得到正确结果。
代码:
#include<stdio.h>
#define maxn 100000+5
int Array[maxn];
int main()
{
intN;
while(scanf("%d",&N)==1)
{
intans=1;
ints=0;
intl,d;
for(int i=0;i<N;i++)
scanf("%d",&Array[i]);
while(s<N-1)
{
l=s+1;
d=Array[l]-Array[l-1];
while(l<N&&Array[l]-Array[l-1]==d)
l++;
l--;
if(l-s+1>ans)
ans=l-s+1;
s=l;
}
printf("%d\n",ans);
}
return0;
}
解题感想:最开始的想法比较笨,思路大致如下:将所有的公差用一个数组存起来,然后找出公差数组中连续相等的最大值,将其加一即为所求。以样例为例:给出的数组为{1,4,7,9,11,14},那么对应的公差数组为{3,3,2,2,3},连续相等的最大值为2,所以输出结果为3,按照这个思路交代码一直编译错误,改成上面的思路后还是编译错误。本来是用const定义maxn的,改成#define就没有编译错误,所以按照之前思路编的代码应该也是对的,可惜之前的代码直接被我删掉了,以后会注意把所有的思路代码都保存好