272. 最长公共上升子序列

版权声明:转载请注明出处 https://blog.csdn.net/qq_37708702/article/details/89741167

题目链接
熊大妈的奶牛在小沐沐的熏陶下开始研究信息题目。

小沐沐先让奶牛研究了最长上升子序列,再让他们研究了最长公共子序列,现在又让他们研究最长公共上升子序列了。

小沐沐说,对于两个数列A和B,如果它们都包含一段位置不一定连续的数,且数值是严格递增的,那么称这一段数是两个数列的公共上升子序列,而所有的公共上升子序列中最长的就是最长公共上升子序列了。

奶牛半懂不懂,小沐沐要你来告诉奶牛什么是最长公共上升子序列。

不过,只要告诉奶牛它的长度就可以了。

数列A和B的长度均不超过3000。

输入格式
第一行包含一个整数N,表示数列A,B的长度。

第二行包含N个整数,表示数列A。

第三行包含N个整数,表示数列B。

输出格式
输出一个整数,表示最长公共子序列的长度。

数据范围
1≤N≤3000,序列中的数字均不超过231−1

输入样例:
4
2 2 1 3
2 1 2 3

输出样例:
2

在这里插入图片描述

#include<bits/stdc++.h>
#define pf printf
using namespace std;
const int N = 5e2 + 10;
int n,m,la,lb,cur,ans,maxv,a[N],b[N],path[N],dp[N][N]; 
int main(){
	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++){
		maxv = 1;
		for(int j = 1;j <= n;j++){
			dp[i][j] = dp[i - 1][j];
			if(a[i] == b[j]) dp[i][j] = max(dp[i][j],maxv);
			else if(a[i] > b[j]) maxv = max(maxv,dp[i][j] + 1);
		}
	}			
	for(int i = 1;i <= n;i++) ans = max(ans,dp[n][i]);
	printf("%d\n",ans);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_37708702/article/details/89741167