最长公共上升子序列
熊大妈的奶牛在小沐沐的熏陶下开始研究信息题目。
小沐沐先让奶牛研究了最长上升子序列,再让他们研究了最长公共子序列,现在又让他们研究最长公共上升子序列了。
小沐沐说,对于两个数列A和B,如果它们都包含一段位置不一定连续的数,且数值是严格递增的,那么称这一段数是两个数列的公共上升子序列,而所有的公共上升子序列中最长的就是最长公共上升子序列了。
奶牛半懂不懂,小沐沐要你来告诉奶牛什么是最长公共上升子序列。
不过,只要告诉奶牛它的长度就可以了。
数列A和B的长度均不超过3000。
输入格式
第一行包含一个整数N,表示数列A,B的长度。
第二行包含N个整数,表示数列A。
第三行包含N个整数,表示数列B。
输出格式
输出一个整数,表示最长公共子序列的长度。
数据范围
1≤N≤30001≤N≤3000,序列中的数字均不超过231−1231−1
输入样例:
4 2 2 1 3 2 1 2 3
输出样例:
2https://wenku.baidu.com/view/3e78f223aaea998fcc220ea0.html
二维 1 #include <iostream>
2 #include <cstring>
3 #include <algorithm>
4 #include <cstdio>
5 #include <vector>
6 using namespace std;
7
8 typedef long long ll;
9
10 int n;
11 const int N=3005;
12 int arr[N],brr[N],dp[N][N];
13
14 int main(){
15 ios::sync_with_stdio(false);
16 cin>>n;
17 for(int i=1;i<=n;i++) cin>>arr[i];
18 for(int j=1;j<=n;j++) cin>>brr[j];
19 for(int i=1;i<=n;i++){
20 int maxx=0;
21 for(int j=1;j<=n;j++){
22 dp[i][j]=dp[i-1][j]; //A中前i个字母 B中以brr[j]结尾
23 if(arr[i]>brr[j]&&maxx<dp[i-1][j]){ //找前面比brr[j]小的最长公共上升子序列
24 maxx=dp[i-1][j];
25 }
26 if(arr[i]==brr[j]) dp[i][j]=maxx+1;
27 }
28 }
29 int maxx=0;
30 for(int i=1;i<=n;i++){
31 maxx=max(dp[n][i],maxx);
32 }
33 cout << maxx << endl;
34 return 0;
35 }

1 #include <iostream>
2 #include <cstring>
3 #include <algorithm>
4 #include <cstdio>
5 #include <vector>
6 using namespace std;
7
8 typedef long long ll;
9
10 int n;
11 const int N=3005;
12 int arr[N],brr[N],dp[N];
13
14 int main(){
15 ios::sync_with_stdio(false);
16 cin>>n;
17 for(int i=1;i<=n;i++) cin>>arr[i];
18 for(int j=1;j<=n;j++) cin>>brr[j];
19 for(int i=1;i<=n;i++){
20 int maxx=0;
21 for(int j=1;j<=n;j++){
22 if(arr[i]>brr[j]&&maxx<dp[j]){
23 maxx=dp[j];
24 }
25 if(arr[i]==brr[j]) dp[j]=maxx+1;
26 }
27 }
28 int maxx=0;
29 for(int i=1;i<=n;i++){
30 maxx=max(dp[i],maxx);
31 }
32 cout << maxx << endl;
33 return 0;
34 }
