Luogu P1439 Longest Common subsequence (LCS problem), p1439lcs
Description
Give two 1-n arrays P1 and P2, and find their longest common subsequences.
Input/Output Format
Input Format:
The first row is a number n,
In the next two rows, the number of n rows is an arrangement of 1-n natural numbers.
Output Format:
A number, that is, the length of the longest common subsequence
Input and Output sample input sample #1: Copy
5 3 2 1 4 51 2 3 4 5
Output example #1: Copy
3
Description
[Data scale]
For 50% of data, n ≤ 1000
For 100% of data, n ≤ 100000
First, hash the number in the first sequence in the second sequence.
Then it becomes the problem of finding the longest ascending subsequence.
You can use binary lookup to solve this problem.
Find the first location equal to or greater
Replace
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 using namespace std; 5 const int MAXN=100001; 6 inline int read() 7 { 8 char c=getchar();int x=0,f=1; 9 while(c<'0'||c>'9') {if(c=='-')f=-1;c=getchar();}10 while(c>='0'&&c<='9') x=x*10+c-48,c=getchar();return x*f;11 }12 int a[MAXN];13 int b[MAXN];14 int ans[MAXN],tot=0;15 int main()16 {17 int n;18 scanf("%d",&n);19 for(int i=1;i<=n;i++) 20 {int p=read();21 a[p]=i;}22 for(int i=1;i<=n;i++) 23 {int p=read();24 b[i]=a[p];}25 for(int i=1;i<=n;i++)26 {27 int p=lower_bound(ans+1,ans+tot+1,b[i])-ans;28 ans[p]=b[i];29 if(p==tot+1) tot++;30 }31 printf("%d",tot);32 return 0;33 }