Arithmetic Sequence
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 1815 Solved: 315
[ 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.
找出最长的等差序列,输出长度
二维dp,第二维记录公差
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int num[2020],dp[2020][2020];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
memset(num,0,sizeof(num));
for(int i=0;i<2020;i++)
{
for(int j=0;j<2020;j++)
dp[i][j]=1;
}
for(int i=1;i<=n;i++)
{
scanf("%d",&num[i]);
}
sort(num+1,num+n+1);
int ans=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<i;j++)
{
int d=num[j]-num[i];
dp[i][d]=max(dp[i][d],dp[j][d]+1);
ans=max(dp[i][d],ans);
}
}
printf("%d\n",ans);
}
return 0;
}
本文介绍了一种通过二维动态规划解决寻找最长等差数列问题的方法。输入为一系列正整数,目标是在这些数中找到最长的等差数列,并输出其长度。算法首先对输入进行排序,然后使用动态规划记录不同等差数列的最大长度。
&spm=1001.2101.3001.5002&articleId=51423442&d=1&t=3&u=f4686773e3eb4a248b87f0401d584bba)
162

被折叠的 条评论
为什么被折叠?



