NYOJ

来源:互联网 发布:淘宝装修一键安装 编辑:程序博客网 时间:2024/06/11 15:09
Problem Description
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.
Input
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;
Output
For each set of test cases, output the length of the longest common subsequence of A and B, in a single line.
Sample Input
5 41 2 6 5 41 3 5 4
Sample Output
3
题目思路

  题目意思很明确,要求两个序列的最长公共子序列,但是这两个序列的长度较大,我们知道求LCS使用动态规划的思想的时间复杂度是O(N^2)。根据题目的时间限制,一定是不能使用这种方法求解的。而我们又没办法优化它。

  题目中有一个很关键的条件是:Each element in the sequence are different,元素是唯一的,因此,如果两个序列都出现了某个元素,那么这些元素可能组成最长公共子序列,即两个子序列都有的元素。但是出现的顺序可以不相同。那么我们需要求出的就是出现顺序相同的一个序列。如果第一个序列的元素在第二个序列中出现,那我们用一个数组来保存这个元素在第一个序列中的下标。那么我们求出这个新的序列的最长上升子序列的长度,就是答案。

  而一般的求解LIS的方法的时间复杂度仍然是O(N^2)但是我们可以把他优化到O(NlogN)。因此求解该题目的思路就是:

  1.先通过处理两个序列的元素生成第三个序列

  2.用时间复杂度为O(NlogN)的求LIS的方法求出序列三的LIS

题目代码
#include <cstdio> #include <iostream>#include <map>#include <set>#include <vector>#include <cmath>#include <string>#include <cstring>#include <algorithm>#define LL long long #define INF 100001using namespace std;int n, m, len;int dp[100001];int a[100001], b[100001],x;int binarySearch(int x){int l, r, mid;l = 1; r = len;while(l < r){mid = (r + l) / 2;if(x <= dp[mid])r = mid ;elsel = mid + 1;}return l;}int main(){while(scanf("%d%d",&n,&m) != EOF){//init and input memset(a, 0, sizeof(a));for(int i = 0; i <= m; i++) dp[i] = INF;for(int i = 1; i <= n; i++){scanf("%d", &x);a[x] = i;}int j = 0;for(int i = 1; i <= m; i++){scanf("%d", &x);if(a[x]) b[++j] = a[x];}// data prcessing dp[1] = b[1]; len = 1;for(int i = 2; i <= j; i++){if(b[i] > dp[len]){dp[++len] = b[i];} else{//int pos = lower_bound(dp,dp+j,b[i])-dp ;  使用STL            int pos = binarySearch(b[i]);dp[pos] = b[i];}}printf("%d\n",len);}return 0;}


1 0
原创粉丝点击