week10——B - LIS & LCS

topic

Dongdong has two sequences A and B.
He wants to know the length of the LIS of sequence A and the LCS of sequence AB.
Note that LIS is strictly increasing, that is, a1<a2<...<ak(ai<=1,000,000,000).

Input

Two numbers in the first line n, m (1<=n<=5,000,1<=m<=5,000)

The number of n in the second line represents the sequence A

The number of m in the third line represents the sequence B

Output

Output a row of data ans1 and ans2, which represent the length of the LIS of sequence A and the LCS of sequence AB, respectively

Simple Input

5 5

1 3 2 5 4

2 4 3 1 5

Simple Output

3 2

Ideas

Insert picture description here
Insert picture description here

error

1. Forgot to enter n and m.
2. You don’t need to use recursion for this question, just use nested for loop, because when calculating f[i][j], the previous ones of f[i][j] have already been calculated

Code

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
//可能需要二分orz 
const int maxn=5010;
long long a[maxn];
long long b[maxn];
int f[maxn];
int f2[maxn][maxn]={
    
    };
int main()
{
    
    
 int n,m,ans1=0;
 cin>>n>>m;
 for(int i=1;i<=n;i++)
  scanf("%lld",&a[i]);
 for(int i=1;i<=m;i++)
  scanf("%lld",&b[i]);
 //LIS 最长上升子序列 
 f[1]=1;
 for(int i=2;i<=n;i++)
 {
    
    
  int maxx=0;
  for(int j=1;j<i;j++)
  {
    
    
   if(a[j]<a[i]&&f[j]>maxx)
    maxx=f[j];
  }
  f[i]=maxx+1;
  } 
  for(int i=1;i<=n;i++)
   if(f[i]>ans1)
    ans1=f[i];
 cout<<ans1<<' ';
 
 f2[1][0]=0;
 f2[0][1]=0;
 f2[0][0]=0;
 for(int i=1;i<=n;i++)
  for(int j=1;j<=m;j++)
  {
    
    
   if(a[i]==b[j])
    f2[i][j]=f2[i-1][j-1]+1;
   else
    f2[i][j]=max(f2[i-1][j],f2[i][j-1]);
  }
 cout<<f2[n][m]<<endl;
 return 0;
}

Guess you like

Origin blog.csdn.net/alicemh/article/details/105799423