HZAU 1019 Arithmetic Sequence

题目链接

Description

给你一串数,找出最长的等差数列

Algorithm

动态规划
先排序
dp[i][j] 表示 到 第i个数 以公差为 j 的 最长等差数列数
假设排好序的数列为b
很容易推出状态转移方程
dp[j][b[j] - b[i]] = dp[i][b[j]-b[i]] + 1;
递推即可

Code

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int n;
const int maxn = 2000 + 9;
int a[maxn];
int dp[maxn][maxn];
int b[maxn];
void solve()
{
  memset(a, 0, sizeof(a));
  memset(dp, 0, sizeof(dp));
  memset(b, 0, sizeof(b));
  for (int i = 0; i < n; i++)
    scanf("%d", &a[i]);
  sort(a, a + n);
  b[0] = a[0];
  dp[0][0]++;
  int b_size = 1;
  for (int i = 1; i < n; i++) {
    if (a[i] != b[b_size - 1]) {
      b[b_size++] = a[i];
    }
    dp[b_size - 1][0]++;
  }
  int ans2 = 0;
  for (int i = 0; i < b_size; i++)
    if (dp[i][0] > ans2)
      ans2 = dp[i][0];
  for (int i = 0; i < b_size; i++) {
    for (int j = i + 1; j < b_size; j++) {
      dp[j][b[j] - b[i]] = dp[i][b[j]-b[i]] + 1;
    }
  }
  int ans = 0;
  for (int i = 0; i < b_size; i++)
    for (int j = 1; j < maxn; j++)
      if (dp[i][j] > ans)
        ans = dp[i][j];
  ans++;
  if (ans2 > ans) ans = ans2;
  cout << ans << endl;
}
int main()
{
// freopen("input.txt", "r", stdin);
  while (scanf("%d", &n) != EOF)
    solve();
}

你可能感兴趣的:(HZAU 1019 Arithmetic Sequence)