题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1055
基准时间限制:2 秒 空间限制:262144 KB 分值: 80
难度:5级算法题
N个不同的正整数,找出由这些数组成的最长的等差数列。
例如:1 3 5 6 8 9 10 12 13 14
等差子数列包括(仅包括两项的不列举)
1 3 5
1 5 9 13
3 6 9 12
3 8 13
5 9 13
6 8 10 12 14
其中6 8 10 12 14最长,长度为5。
Input
第1行:N,N为正整数的数量(3 <= N <= 10000)。 第2 - N+1行:N个正整数。(2<= A[i] <= 10^9)
Output
最长等差数列的长度。
Input示例
10 1 3 5 6 8 9 10 12 13 14
Output示例
5
sol:
比较详细的解法:https://www.geeksforgeeks.org/length-of-the-longest-arithmatic-progression-in-a-sorted-array/
用dp[i]][j]表示序列前2位是a[i],a[j]序列最大的等差数列最大长度,应该从后往前递推。
更新的时候,固定j,往两边O(n)扫描,如果a[i]+a[k]=2*a[j](即构成等差数列),则dp[i][j]=dp[j][k]+1;
注意这里用int会爆内存。
code:
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<string>
#include<map>
#include<cmath>
#include<unordered_map>
using namespace std;
const int maxn = 1e4+5;
const int inf = 0x3f3f3f3f;
const int mod = 1000000007;
typedef long long ll;
typedef pair<int,int> pi;
int a[maxn];
short dp[maxn][maxn];
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
if(n==1){
cout<<1<<endl;
exit(0);
}
sort(a+1,a+n+1);
for(int i=1;i<n;i++)
for(int j=i+1;j<=n;j++) dp[i][j]=2;
short ans = 2;
for(int j=n-1;j>1;j--){
int i=j-1;
int k=j+1;
while(i>0&&k<=n){
while(a[i]+a[k]>2*a[j]&&i) i--;
while(k<=n&&a[i]+a[k]<2*a[j]) k++;
if(a[i]+a[k]==2*a[j]) dp[i][j]=dp[j][k]+1;
i--;
}
}
for(int i=1;i<n;i++)
for(int j=1;j<=n;j++) ans=max(ans,dp[i][j]);
cout<<ans<<endl;
return 0;
}