[P1439]【模板】最长公共子序列
【原题】
题目描述
给出 \(1,2,…,n\) 的两个排列 \(P1\)和 \(P2\) ,求它们的最长公共子序列。
输入格式
第一行是一个数 \(n\)。
接下来两行,每行为\(n\)个数,为自然数\(1,2,…,n\) 的一个排列。
输出格式
一个数,即最长公共子序列的长度。
输入输出样例
输入 #1
5
3 2 1 4 5
1 2 3 4 5
输出 #1
3
说明/提示
- 对于 \(50\%\) 的数据,\(n≤10^3\);
- 对于 100%100%100% 的数据,\(n\leq10^5\)。
【思路】
考虑到数据范围 \(n^2\)的dp显然不可行。将序列\(p1\)各个数字出现的位置储存下来,将\(p1\)转化为\(1,2,3......n\)的序列,\(p2\)转化为该位置的数字在\(p1\)出现的位置,如样例的\(p2\)为\(3, 2, 1, 4, 5\) 对转化后的\(p2\)求LICS即为对原序列求公共子序列。时间复杂度\(O(nlogn)\)。
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <list>
#include <map>
#include <iostream>
#include <iomanip>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>
#define LL long long
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f
#define PI 3.1415926535898
#define F first
#define S second
#define endl '\n'
#define lson rt << 1
#define rson rt << 1 | 1
#define f(x, y, z) for (int x = (y), __ = (z); x < __; ++x)
#define _rep(i, a, b) for (int i = (a); i <= (b); ++i)
using namespace std;
const int maxn = 1e5 + 7;
const int maxm = 2e5 + 7;
const int mod = 1e9 + 7;
int n;
int mp[maxn], a[maxn], b[maxn], c[maxn];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
_rep(i, 1, n)
{
cin >> a[i];
mp[a[i]] = i;
}
_rep(i, 1, n)
{
cin >> b[i];
b[i] = mp[b[i]];
}
c[1] = b[1];
int len = 1;
_rep(i, 2, n)
{
if (b[i] > c[len]) c[++len] = b[i];
else
{
int tmp = upper_bound(c + 1, c + 1 + len, b[i]) - c;
c[tmp] = b[i];
}
}
cout << len;
}