华中农业大学第四届程序设计大赛网络同步赛-1020: Arithmetic Sequence

版权声明:本文为博主原创文章,如需转载,请注明来源,多谢合作!! https://blog.csdn.net/NYIST_TC_LYQ/article/details/51425624

1020: Arithmetic Sequence

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 1834  Solved: 322
->打开链接<-

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.


 题意:求一个等差数列,使得长度最长

 思路:先排序a[i],用二维数组b[ ][ ]一维储存公差d,另一维储存这个值(b[ d ][ a[i]+d]),如果这个值存在则二维数组的值加一(b[ d ][ a[i]+d] =b[ d ][ a[i] ]+1),并与当前最大值比较,下次再用当前的(a[i]+d)加上相同的公差d判断得到的值(a[i]+2d)是否存在,如果存在,则b[ d ][ a[i]+2d ] =b[ d ][ a[i] +d ]+1;继续与当前最大长度比较;这样就用的两层for循环,巧妙地避开了超时的问题;如果有疑问请看代码:

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=2000+10;
int a[N],b[N][N],v[N];
int main()
{
    int n,i,j;
    while(~scanf("%d",&n))
    {
        memset(v,0,sizeof(v));
        memset(b,0,sizeof(b));
        for(i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            v[a[i]]=1;//用来判断a[i]+d是否存在;
        }
        if(n<=2)
            printf("%d\n",n);
        else
        {
            sort(a+1,a+1+n);
            int m1=1,m=0,k=a[n]-a[1];//用m储存最大长度;并求出公差最大值;
            for(i=2; i<=n; i++)//公差为0的情况;
            {
                if(a[i]==a[i-1])
                    m1++;
                else
                    m1=1;
                m=max(m,m1);
            }
            for(i=1; i<=n; i++)//两层循环;
            {
                for(j=1; j<=k; j++)//公差的所有可能值,注意公差为0已经在上面判断过了;
                {
                    if(a[i]+j>a[n]) break;
                    if(v[a[i]+j])//如果存在;
                    {
                        if(!b[j][a[i]])
                            b[j][a[i]]=1;表示以a[i]为首项, 公差为d,所以值要赋为1;
                        b[j][a[i]+j]=b[j][a[i]]+1;//关键,这样就是层层更新递推;
                    }
                    m=max(b[j][a[i]+j],m);
//                    printf("%d %d %d\n",i,j,b[j][a[i]+j]);
                }
            }
            printf("%d\n",m);
        }
    }
    return 0;
}
思路确实很好,不过应该有更好的方法思路;恭请指教



展开阅读全文

没有更多推荐了,返回首页