Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:
- a1 = p, where p is some integer;
- ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is some integer.
Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.
Sequence s1, s2, ..., sk is a subsequence of sequence b1, b2, ..., bn, if there is such increasing sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n), that bij = sj. In other words, sequence s can be obtained from b by crossing out some elements.
Input
The first line contains integer n (1 ≤ n ≤ 4000). The next line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106).
Output
Print a single integer — the length of the required longest subsequence.
Examples
Input
2 3 5
Output
2
Input
4 10 20 10 30
Output
3
Note
In the first test the sequence actually is the suitable subsequence.
In the second test the following subsequence fits: 10, 20, 10.
题解一:看到数据很多人会想到dp 我们用dp[i][j] 表示 第i这个位置 向前匹配到 j 这个数 所得到的最大值
那递推关系也就得到了 dp[i][ a[j] ] = dp[j][ a[i] ] + 1 数据很大但数据量不大 离散化一下就可以了
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
const int N=1e6+10;
int n;
int a[N],id[N],dp[4100][4100];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
id[i]=a[i];
}
sort(id+1,id+1+n);
int len=unique(id+1,id+1+n)-(id+1);
for(int i=1;i<=n;i++)
a[i]=lower_bound(id+1,id+1+n,a[i])-id;
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<i;j++)
{
dp[i][a[j]]=dp[j][a[i]]+1;
ans=max(ans,dp[i][a[j]]);
}
}
cout<<ans+1<<endl;
return 0;
}
题解二:当然我们也可以贪心来做,先保存下有多少的不同的数,记录下每个数的位置,然后贪心一下就可以了
千万别用mp标记枚举的那两个数,会在68个超时的..因为我已经试过了
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
const int N=1e6+10;
vector<int> v[N],vp;
int n;
int a[N],id[N];
map<int,int> mp;
int main()
{
scanf("%d",&n);
int ans=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
v[a[i]].push_back(i);
if(v[a[i]].size()>ans) ans=v[a[i]].size();
if(!mp[a[i]]) vp.push_back(a[i]),mp[a[i]]=1;
}
int len=vp.size();
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
int x=vp[i],y=vp[j];
int l1=v[x].size();
int l2=v[y].size();
int l=0,r=0;
int cnt=1;
while(l<l1&&r<l2)
{
while(r<l2&&v[y][r]<v[x][l])
r++;
if(r<l2) cnt++;
else break;
while(r<l2&&l<l1&&v[x][l]<v[y][r])
l++;
if(l<l1&&r<l2) cnt++;
else break;
}
if(v[y][0]<v[x][0]) cnt++;
ans=max(ans,cnt);
}
}
printf("%d\n",ans);
return 0;
}