HAZU 等差数列 dp

来源:互联网 发布:企业网站seo 编辑:程序博客网 时间:2024/05/16 13:39

Arithmetic Sequence

Time Limit: 1 Sec  Memory Limit: 128 MB

Description

    Giving a number sequence Awith length n, you should choosingm numbers fromA(ignore the order) which can form an arithmetic sequence and makem as large as possible.

Input

  There are multiple test cases. In each test case, the first line contains a positive integern. The second line containsn integers separated by spaces, indicating the number sequenceA. All the integers are positive and not more than 2000. The input will end by EOF.

Output

  For each test case, output the maximum as the answer in one line.

Sample Input

51 3 5 7 1084 2 7 11 3 1 9 5

Sample Output

46

HINT



  In the first test case, you should choose 1,3,5,7 to form the arithmetic sequence and its length is 4.


  In the second test case, you should choose 1,3,5,7,9,11 and the length is 6.




题意:给你一个序列,找出最长的等差数列。


做法:先排序,然后从后往前扫描,dp[i][A[j]-A[i]]=dp[j][A[j]-A[i]]+1,表示以a[i]为首项,公差为a[j]-a[i]的等差数列,所有数都相同的时候要特判,不然超时很惨的。



<pre name="code" class="cpp">#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<map>using namespace std;struct node{    int x,y;};bool cmp(node a,node b){if(a.x==b.x)return a.y<b.y;return a.x<b.x;}const int maxn=2000*1000+20;int A[2000+20],det[maxn]; int dp[2000+20][2000+20];int main(void){    int n;    while(~scanf("%d",&n)){        memset(dp,0,sizeof(dp));int x=0;        for(int i=0;i<n;i++){            scanf("%d",A+i);        }        for(int i=1;i<n;i++){        if(A[i]==A[i-1])        x++;            }        if(x==n-1){            printf("%d\n",n);            continue;        }        sort(A,A+n);        int res=0;        for(int i=n-1;i>=0;i--){            for(int j=i+1;j<n;j++){                dp[i][A[j]-A[i]]=dp[j][A[j]-A[i]]+1;                res=max(res,dp[i][A[j]-A[i]]);            }        }        printf("%d\n",res+1);    }     return 0;}


0 0