传送门

 

无重复元素的LCS问题

n2 做法不说了。

 

nlogn 做法 ——

因为LCS问题求的是公共子序列,顺序不影响答案,影响答案的只是两个串的元素是否相同,所以可以交换元素位置。

首先简化一下问题,假设P1恰好为单调递增的1,2,3,...n,那么很显然答案就是P2的最长上升子序列的长度

问题是P1并非单调递增的,但我们可以假定它就是1,2,3,...,n。

也就是重新定义一下第一个串中 所有数 的顺序,定义a[x] = i,也就是 数x 是第 i 个,然后再重新弄一下第二串的顺序,最后求一遍lis。

 

——代码

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 const int MAXN = 100001;
 8 int n, ans;
 9 int a[MAXN], b[MAXN], c[MAXN];
10 
11 inline int query(int x)
12 {
13     int ans = 0;
14     for(; x; x -= x & -x) ans = max(ans, c[x]);
15     return ans;
16 }
17 
18 inline void update(int x, int d)
19 {
20     for(; x <= n; x += x & -x) c[x] = max(c[x], d);
21 }
22 
23 int main()
24 {
25     int i, j, x, y;
26     scanf("%d", &n);
27     for (i = 1; i <= n; i++) scanf("%d", &x), a[x] = i;
28     for (i = 1; i <= n; i++) scanf("%d", &x), b[i] = a[x];
29     for(i = 1; i <= n; i++)
30     {
31         y = query(b[i] - 1) + 1;
32         update(b[i], y);
33         ans = max(ans, y);
34     }
35     printf("%d", ans);
36     return 0;
37 }
View Code

相关文章:

  • 2021-06-21
  • 2022-12-23
  • 2021-10-18
  • 2021-11-13
  • 2021-12-10
  • 2021-04-15
  • 2021-06-29
  • 2022-03-08
猜你喜欢
  • 2022-01-12
  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
  • 2021-09-01
相关资源
相似解决方案