Arithmetic Progressions

一、问题

An arithmetic progression is a sequence of numbers a_1, a_2, . . . , a_ka1​,a2​,...,ak​ where the difference of consec- utive members ai+1 − ai is a constant (1 ≤ i ≤ k − 1). For example, the sequence 5, 8, 11, 14, 17 is an arithmetic progression of length 5 with the common difference 3.In this problem, you are requested to find the longest arithmetic progression which can be formed selecting some numbers from a given set of numbers. For example, if the given set of numbersis {0, 1, 3, 5, 6, 9}, you can form arithmetic progressions such as 0, 3, 6, 9 with the common difference 3, or 9, 5, 1 with the common difference −4. In this case, the progressions 0, 3, 6, 9 and 9, 6, 3, 0 are the longest.

题目大意:给定 N(1<N<=5000) 个不同元素组成的集合,求从中选出若干数字组成的最长等差数列的长度是多少。

二、解题思路

(1)最优子结构

有一串数组为<x1,x2,x3,x4,x5,x6,...>,设xi,xj分别为某个最长等差数列的倒数第2个元素和倒数第1个元素,则长度记为L<xi,xj>,则这个等差数列的长度L<xi, xj> = L<xt, xi>,其中0<=t<i。

(2)构造递归表达式

          d[0][j] = 2, 1<j<n;

          d[i][j] = max{2, d[t][i] + 1}, 0<t<i;

三、代码

#include <iostream>
#include <algorithm>

using namespace std;
const int N =  5010;
int d[N][N] = {0};
int a[N] = {0};

int main (){
    int n;
    cin>>n;
    for(int i = 0; i < n; i++){
        cin>>a[i];
    }
    sort(a, a + n);

    for(int j = 1; j < n; j++){
        d[0][j] = 2;
    }
    int max = 2;
    for(int i = 1; i < n - 1; i++){
        for(int j = i + 1; j < n; j++){
            d[i][j] = 2;
            for(int t = 0; t < i; t++){
                if(a[j] - a[i] == a[i] - a[t]){
                    d[i][j] = d[t][i] + 1;
                    if(d[i][j] > max){
                        max = d[i][j];
                    }
                }
            }
        }
    }

    cout<<max<<endl;

    return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值