badge:
Ordinary O (n ^ 2) is very easy to think, but TLE.
#include<cstdio>
using namespace std;
int a[1010],b[1010],dp[1010][1010];
int maxf(int x,int y){return x>y?x:y;}
int minf(int x,int y){return x<y?x:y;}
int main()
{
int n,m,i,j,k;
scanf("%d",&n);
for(i=1;i<=n;i++)scanf("%d",&a[i]);
for(i=1;i<=n;i++)scanf("%d",&b[i]);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
dp[i][j]=maxf(dp[i][j],maxf(dp[i-1][j],dp[i][j-1]));
if(a[i]==b[j])
dp[i][j]=maxf(dp[i][j],dp[i-1][j-1]+1);
}
}
printf("%d\n",dp[n][n]);
return 0;
}
We ponder this question key points: 1 to two sequences are aligned to n.
arrangement? This means that the two sequences in number are the same, just a different location.
Somewhat similar to sister city, just a bunch of requirements pairing can not intersect.
FIG be drawn, the sequence of each left right according to the position where the number of re-fill, find a longest sequence to rise.
Namely: a recording sequence number in each filling position f [a [i]] = i, then b [i] assigned to f [b [i]]. B in sequence in O (nlogn) LIS can find it.
#include<cstdio>
using namespace std;
int a[1000010],b[1000010];
int c[1000010],f[1000010],tot;
int pos(int l,int r,int val)
{
int mid,ans;
while(l<=r)
{
mid=(l+r)>>1;
if(c[mid]>val)r=mid-1,ans=mid;
else l=mid+1;
}
return ans;
}
int main()
{
int n,m,i,j,k;
scanf("%d",&n);
for(i=1;i<=n;i++)scanf("%d",&a[i]);
for(i=1;i<=n;i++)scanf("%d",&b[i]);
for(i=1;i<=n;i++)f[a[i]]=i;
for(i=1;i<=n;i++)b[i]=f[b[i]];
//for(i=1;i<=n;i++)printf("%d ",f[i]);printf("\n");
//for(i=1;i<=n;i++)printf("%d ",b[i]);printf("\n");
c[++tot]=b[1];
for(i=2;i<=n;i++)
{
if(b[i]>c[tot])c[++tot]=b[i];
else
{
k=pos(1,tot,b[i]);
//printf("found pos %d\n",k);
c[k]=b[i];
}
}
printf("%d\n",tot);
return 0;
}
/*
5
3 2 1 4 5
1 2 3 4 5
*/