链接:戳这里
21: Arithmetic Sequence
Time Limit: 1 Sec Memory Limit: 128 MB
[Submit][Status][Web Board]
Description
Giving a number sequence A with length n, you should choosing m numbers from A(ignore the order) which can form an arithmetic sequence and make m as large as possible.
Input
There are multiple test cases. In each test case, the first line contains a positive integer n. The second line contains n integers separated by spaces, indicating the number sequence A. 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.
Source
题意:
给出n个元素,取出m个数使得这m个数位等差数列,求出最大的m
0<n<2000 0<a[i]<2000
思路:
dp[i][j] 表示以第i个元素为结尾的等差数列,公差为j的个数
dp[i][j]=dp[前一个数a'使得a[i]-a'=j ][j]+1
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include <ctime>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<iomanip>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
#define MAX 1000100
///#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
typedef unsigned long long ull;
#define INF (1ll<<60)-1
using namespace std;
int n;
int a[2010];
int vis[2010];
int dp[2010][2010]; ///以第i个结尾的等差数列,公差为j的个数
int main(){
while(scanf("%d",&n)!=EOF){
mst(vis,0);
mst(dp,0);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
for(int j=0;j<2000;j++)
dp[i][j]=1;
int ans=1;
for(int i=1;i<=n;i++){
for(int j=0;j<2000;j++){
if(a[i]-j>=0) dp[i][j]=dp[vis[a[i]-j]][j]+1;
ans=max(ans,dp[i][j]);
}
vis[a[i]]=i;
}
cout<<ans<<endl;
}
return 0;
}