B.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
错误代码:
#include<iostream>
using namespace std;
int main(){
int n;
int k;
int flag=1;
int p[100000];
while(cin>>n){
for(int i=0;i<n;i++){
cin>>p[i];
}
if(n==1){flag=0;}
else if(n==2){flag=1;}
else{
for(int j=0;j+2<n;j++){
k=p[j+1]-p[j];
if(k==p[j+2]-p[j+1]){flag++;}
else{
j=flag;
break;}}}
cout<<(flag+1)<<endl;
}
return 0;
}
这个代码总是提示超时,所以很长时间我在想办法进行优化,但是尝试数次后,依旧还是超时,在后来拿到测试数据后,进行测试,发现,着代码的答案根本就好似错误的,我理解错了题目的意思,这个代码求得是一系列数字的最大的相邻差,我很不理解为什么判定系统为什么仅仅是判定超时
正确代码:
题目的正确意思是在一串数字中找到最长的等差数列,并且将等差数列的个数输出,由于题目给出的数据的巧合,我很长时间认为是在求最大相邻差值,在进行此代码输入的时候,曾很长时间#include<iostream> using namespace std; inline int fun(int *p,int k,int h){ int x=1; for(int m=0;m+h+1<k;m++){ if(p[h]==p[m+h+1]-(m+1)*(p[h+1]-p[h])){x++;} else{break;} } return x;} int main(){ int n; int num[100001]; int z=1; while(cin>>n){ for(int i=0;i<n;i++){ cin>>num[i];} if(n==1){cout<<"1"<<endl;} if(n==2){cout<<"2"<<endl;} if(n>=3){ int j=0; z=fun(num,n,j); j=j+z; while(j<n){ if(z<fun(num,n,j-1)){ z=fun(num,n,j-1); j=j+z-1; } else{j=j+fun(num,n,j-1)-1;} } cout<<z<<endl;; } } return 0; }
j=j+z;这让我纠结很久,无论这个位置向后的第一组等差数列是不是最长的,都往后移动的的数组个数都应该是这个数列的个数