Luogu P1439 【Template】Longest common subsequence

God TM template. . I wanted to take a break and write some water questions. . .

When I started to do it, I directly typed an O(N 2 ) algorithm, and when I compiled it, I found that it could not be opened at all. .

Alright, back to the subject.

Give an algorithm without proof.

If there is a set of data
2
4 2 5 1 3
2 5 4 1 3
Then we make
4 2 5 1 3
| | | | |
1 2 3 4 5
The data in the third row becomes
2 3 1 4 5
Obviously, the answer is the longest ascending subsequence of this data, that is, 4 == 2 3 4 5, which is 2 5 1 3 of the original sequence.

Now let's briefly introduce the reasons for this.

First, observe the problem and notice the difference between this problem and the real template: two permutations of 1-n are given, P1 and P2.

Think about the nature of permutations, and that each number from 1-N will occur only once.

Quoting a sentence in Luogu's solution, because the longest common subsequence is aligned bitwise backwards, if the position of each element of the a sequence in the b sequence increases, it means that the number in b is the same as the one in a. After the overall position of the number is offset , it can be considered to be included in the LCS - then it can be converted into the LIS in the map array that nlogn is used to record the new position .

So you can write code.

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAXN = 1e5 + 20;
 4 const int INF = 0x3f3f3f3f;
 5 
 6 inline int read()
 7 {
 8     int x = 0; char ch = getchar();
 9     while(!isdigit(ch)) ch = getchar();
10     while(isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
11     return x;
12 }
13 
14 int N;
15 int a[MAXN], f[MAXN];
16 
17 int main()
18 {
19     cin>>N;
20     for(int i = 1; i <= N; i++)
21         a[read()] = i;
22 
23     memset(f, 0x3f, sizeof(f));
24     int cur;
25     for(int i = 1; i <= N; i++)
26     {
27         cur = a[read()];
28         *lower_bound(f, f + N + 1, cur) = cur;
29     }
30 
31     cout<<(lower_bound(f, f + N + 1, INF) - f)<<endl;
32     return 0;
33 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325048115&siteId=291194637