NYOJ - 760 - See LCS again(最长上升子序列O(N(logN)实现)

本文介绍了一种利用最长上升子序列(LIS)优化算法解决最长公共子序列(LCS)问题的方法,针对序列中元素唯一的特点,通过预处理生成新序列,并采用O(NlogN)的时间复杂度求解LIS,从而高效地找到两个较长序列的最长公共子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 4
1 2 6 5 4
1 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 100001

using 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 ;
		else
			l = 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值