[P1439]【模板】最長公共子序列
阿新 • • 發佈:2020-08-06
【原題】
題目描述
給出 \(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\)
#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; }