See LCS again
时间限制:1000 ms | 内存限制:65535 KB
难度:3
-
描述
-
There are A, B two sequences, the number of elements in the sequence is n、m;
Each element in the sequence are different and less than 100000.
Calculate the length of the longest common subsequence of A and B.
-
-
输入
-
The input has multicases.Each test case consists of three lines;
The first line consist two integers n, m (1 < = n, m < = 100000);
The second line with n integers, expressed sequence A;
The third line with m integers, expressed sequence B;
输出
- For each set of test cases, output the length of the longest common subsequence of A and B, in a single line. 样例输入
-
5 4 1 2 6 5 4 1 3 5 4
样例输出
-
3
-
由于数据量,所以把最长公共子序列转化为最长递增子序列 而最长递增子序列由nlogn算法
这就是这个题的经典之处 -
#include <cstdio> #include <algorithm> #include <climits> #include <cstring> using namespace std; #define maxn 100000 int a[maxn + 10]; int b[maxn + 10]; int g[maxn + 10]; int n, m; int main(void){ int i; while(scanf("%d%d", &n, &m) == 2) { int t; memset(a, 0, sizeof(a)); for (i = 1; i <= n; ++i) { scanf("%d", &t); a[t] = i; } int p = 0; for (i = 0; i < m; ++i) { scanf("%d", &t); if(a[t]) { b[p++] = a[t]; } } int mmax = 0; for (i = 1; i <= p; ++i) { g[i] = 100000000; } for (i = 0; i < p; ++i) { int k = lower_bound(g + 1, g + p + 1, b[i]) - g; if(k > mmax) mmax = k; g[k] = b[i]; } printf("%d\n", mmax); } return 0; }
-
The input has multicases.Each test case consists of three lines;