Regulation movable special - the longest common subsequence (LCS)

First a big brother to explain :( strongly recommended)

https://blog.csdn.net/v_july_v/article/details/6695482

LongestCommon Subsequence

Equation of state transition:
i f ( x [ i ] = = Y [ j ] ) : f [ i ] [ j ] = f [ i 1 ] [ j 1 ] + 1 if(x[i]==y[j]): f[i][j]=f[i-1][j-1]+1
i f ( x [ i ] ! = Y [ j ] ) : f [ i ] [ j ] = m a x ( f [ i 1 ] [ j ] , f [ i ] [ j 1 ] ) if(x[i]!=y[j]): f[i][j]=max(f[i-1][j],f[i][j-1])


LCS to a bare title:
https://vjudge.net/problem/HDU-1159

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstdlib>
using namespace std;

string a,b;
int f[500][500];

void clear(){
    for(int i=0;i<500;i++)
        for(int j=0;j<500;j++)
            f[i][j] = 0;
}

void lcs(){
    for(int i=1;i<=a.size();i++){
        for(int j=1;j<=b.size();j++){
            if(a[i-1]==b[j-1]) f[i][j] = f[i-1][j-1]+1;
            else f[i][j] = max(f[i-1][j],f[i][j-1]);
        }
    }

    cout<<f[a.size()][b.size()]<<endl;
}

void solve(){
    while(cin>>a>>b){
        clear();
        lcs();
    }
}

int main(){
    solve();
    system("pause");
    return 0;
}

Variant:
https://www.luogu.org/problemnew/show/P1439

Guess you like

Origin blog.csdn.net/baidu_41560343/article/details/92021851