您的位置:首页 > 其它

HAZU 等差数列

2016-05-15 19:13 253 查看

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

5
1 3 5 7 10
8
4 2 7 11 3 1 9 5

Sample Output

4
6

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;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: