Longest common subsequence rise [optimization]

To two sequences, find the longest common subsequence rise;
Status indicates: F [i] [j]: 1 to 1 i and j to b [j] to the end of the sequence
set max attribute
state transition equation: not divided into a [i]] is set
if not a [i] is f [i] [j] = f [i-1] [j];
if a premise of a [i] [i] [j] == b, then

for(int k=1;k<j;k++){
	if(b[k]<a[i]) f[i][j]=max(f[i][j],f[i-1][k]+1);

Optimization of
Here Insert Picture Description
the maximum value during the above traverse recording MAXV;


    for(int i=1;i<=n;i++){
        int maxv=1;
        for(int j=1;j<=n;j++){
            f[i][j]=f[i-1][j]; // 没有a[i] 的情况
            if(a[i]==b[j]) f[i][j] = max(f[i][j],maxv); 用前缀maxv更新一下f[i][j];
            if(b[j]<a[i]) maxv=max(maxv,f[i-1][j]+1);// 如果b[k] 比a[i] 小,那么就可以更新maxv 
        }
    }

Complete code:

#include<bits/stdc++.h>
using namespace std;
int n;
const int N=3030;
int a[N],b[N],f[N][N];

int main(){
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    for(int i=1;i<=n;i++) cin>>b[i];

    for(int i=1;i<=n;i++){
        int maxv=1;
        for(int j=1;j<=n;j++){
            f[i][j]=f[i-1][j];
            if(a[i]==b[j]) f[i][j] = max(f[i][j],maxv);
            if(b[j]<a[i]) maxv=max(maxv,f[i-1][j]+1);
        }
    }
    int res=0;
    for(int i=1;i<=n;i++) res=max(res,f[n][i]);
    cout<<res<<endl;
    return 0;
}
Published 152 original articles · won praise 4 · Views 3862

Guess you like

Origin blog.csdn.net/qq_43716912/article/details/103706379