洛谷 P1439 【模板】最长公共子序列 题解

每日一题 day40 打卡

Analysis

因为两个序列都是1~n 的全排列,那么两个序列元素互异且相同,也就是说只是位置不同罢了,那么我们通过一个book数组将A序列的数字在B序列中的位置表示出来

因为最长公共子序列是按位向后比对的,所以a序列每个元素在b序列中的位置如果递增,就说明b中的这个数在a中的这个数整体位置偏后,可以考虑纳入LCS——那么就可以转变成nlogn求用来记录新的位置的book数组中的LIS

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #define maxn 100000+10
 6 #define INF 9187201950435737471
 7 #define rep(i,s,e) for(register int i=s;i<=e;++i)
 8 #define dwn(i,s,e) for(register int i=s;i>=e;--i) 
 9 using namespace std;
10 inline int read()
11 {
12     int x=0;
13     bool f=1;
14     char c=getchar();
15     for(; !isdigit(c); c=getchar()) if(c=='-') f=0;
16     for(; isdigit(c); c=getchar()) x=(x<<3)+(x<<1)+c-'0';
17     if(f) return x;
18     return 0-x;
19 }
20 inline void write(int x)
21 {
22     if(x<0){putchar('-');x=-x;}
23     if(x>9)write(x/10);
24     putchar(x%10+'0');
25 }
26 int n,ans=1;
27 int a[maxn],b[maxn],book[maxn],last[maxn];
28 signed main()
29 {
30     n=read();
31     rep(i,1,n) a[i]=read(),book[a[i]]=i;
32     rep(i,1,n) b[i]=read();
33     last[1]=book[b[1]];
34     rep(i,2,n)
35     {
36         if(book[b[i]]>=last[ans]) last[++ans]=book[b[i]];
37         else 
38         {
39             int num=upper_bound(last+1,last+ans+1,book[b[i]])-last;
40             last[num]=book[b[i]];
41         }
42     }
43     write(ans);
44     return 0;
45 }

请各位大佬斧正(反正我不认识斧正是什么意思)

原文地址:https://www.cnblogs.com/handsome-zyc/p/11851736.html