\(n^2\)做法
f[i][j]=max(f[i][j], f[i-1][j-1]+1);
反之则f[i][j]=max(f[i][j], max(f[i][j-1], f[i-1][j]))
#include <algorithm>
#include <cstdio>
using namespace std;
int n, a[1003], b[1003], f[1003][1003], ans;
int main() {
int n; scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (a[i] == b[j]) ans = max(ans, f[i][j] = max(f[i][j], f[i-1][j-1]+1));
else f[i][j] = max(max(f[i-1][j], f[i][j]),f[i][j-1]);
printf("%d", f[n][n]);
return 0;
}
\(nlogn\)做法(这方法妙得一匹)
感性理解正确性:由于两个序列是\(N\)的全排列,A序列中每一个数字在B序列中有唯一一个数对应,公共子序列在B序列中位置是递增的,在A序列中位置也是递增的,正确性显而易见
原文:https://www.cnblogs.com/northpoleforce/p/12961149.html