[DP Hash] 51Nod 1055 最长等差数列

来源:互联网 发布:用友软件版本介绍 编辑:程序博客网 时间:2024/05/18 15:50

讨论帖:http://www.51nod.com/question/index.html#!questionId=79


DP[i,j]表示以第i个数为倒数第2项,第j个数为最后1项,可以组成的等差数列的长度

然后hash记一下一个数上次出现的时间


这是一篇专门解决这个问题的论文
http://www.cs.uiuc.edu/~jeffe/pubs/pdf/arith.pdf

其中有一个分治的思路,就是二分这个最大长度k,然后在集合中找长度为k的序列。由于序列长度为k,将数组分为2段的话,一定有一段中长度大于k/2,所以依靠不断地分治,直到找出所有长度为k的等差数列,然后用了一个定理,保证数量不会太多,从而降低了复杂度。

还没看过


#include<cstdio>#include<cstdlib>#include<algorithm>#include<iostream>using namespace std;const int N=10005;const int P=100007;int n,a[N];short f[N][N],pre[P],ans;int main(){  freopen("t.in","r",stdin);  freopen("t.out","w",stdout);  scanf("%d",&n); ans=1; short tem;  for (int i=1;i<=n;i++) scanf("%d",a+i);  sort(a+1,a+n+1);  for (int i=1;i<n;i++){    for (int j=i+1;j<=n;j++){      if (2*a[i]-a[j]>0 && (tem=pre[(2*a[i]-a[j])%P]))f[i][j]=f[tem][i]+1;      elsef[i][j]=2;      ans=max(ans,f[i][j]);    }    pre[a[i]%P]=i;  }  cout<<ans<<endl;  return 0;}




0 0
原创粉丝点击