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

二、解题思路

(1)最优子结构

有一串数组为,设xi,xj分别为某个最长等差数列的倒数第2个元素和倒数第1个元素,则长度记为L,则这个等差数列的长度L = L,其中0<=t

(2)构造递归表达式

          d[0][j] = 2, 1

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

三、代码

#include 
#include 

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<

 

你可能感兴趣的:(数据结构与算法,C++)