洛谷 P1439 【模板】最长公共子序列
Description
- 给出1-n的两个排列P1和P2,求它们的最长公共子序列。
Input
第一行是一个数n,
接下来两行,每行为n个数,为自然数1-n的一个排列。
Output
- 一个数,即最长公共子序列的长度
Sample Input
5
3 2 1 4 5
1 2 3 4 5
Sample Output
3
Data Size
对于50%的数据,n≤1000
对于100%的数据,n≤100000
题解:
- 转换思想。
- 观察数据范围,n方做法肯定会炸。但我才刚学过LIS的nlogn做法。那这题是否同样可用nlogn解决呢?
- 答案是肯定的。
- 两个序列a和b。把a序列映射成1-n的连续上升序列,b映射后得到了新序列c。答案就是c序列的LIS。因为连续上升序列保证了a是递增的,这时他们的LCS就是他们的最大LIS。
- LIS可用树状数组维护
#include <iostream>
#include <cstdio>
#include <map>
#define lowbit(x) (x & (-x))
#define maxn 100005
using namespace std;
int n, cnt, ans;
int a[maxn], b[maxn], c[maxn];
map<int, int> mp;
int read()
{
int x = 0; char c = getchar();
while(c < '0' || c > '9') c = getchar();
while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
return x;
}
int ask(int pos)
{
int r = 0;
while(pos >= 1)
{
r = max(r, c[pos]);
pos -= lowbit(pos);
}
return r;
}
void update(int pos, int val)
{
while(pos <= n)
{
c[pos] = max(c[pos], val);
pos += lowbit(pos);
}
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++) a[i] = read(), mp[a[i]] = i;
for(int i = 1; i <= n; i++) b[i] = read();
for(int i = 1; i <= n; i++) b[i] = mp[b[i]];
for(int i = 1; i <= n; i++)
{
int t = ask(b[i] - 1) + 1;
update(b[i], t);
ans = max(ans, t);
}
cout << ans;
return 0;
}