最长公共子序列LCS 求法 O(mn) 即输出所有LCS

最长公共子序列LCS 求法 O(mn) 即输出所有LCS

#include <bits/stdc++.h>
using namespace std;
const int N = 1005;

int dp[N][N], flag[N][N];
int a[N], b[N];
int n;
set<string> st;
void printLCS(int i,int j,string str)
{
    while(i > 0 && j > 0)
    {
        if(a[i] == b[j])
        {
            str += a[i] + '0';
            i --;
            j --;
        }
        else
        {
            if(dp[i-1][j] > dp[i][j-1])
                i --;
            else if(dp[i-1][j] < dp[i][j-1])
                j --;
            else
            {
                printLCS(i-1,j,str);
                printLCS(i,j-1,str);
                return ;
            }
        }
    }

    reverse(str.begin(),str.end());
    st.insert(str);

}
int main()
{
    ios::sync_with_stdio(false);

    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 ++)
    {
        for(int j = 1;j <= n;j ++)
        {
            if(a[i] == b[j])
                dp[i][j] = dp[i-1][j-1] + 1;
            else
                dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
        }
    }

    /*输出LCS长度*/
    cout << dp[n][n] << endl;
    
    /*输出所有LCS*/
    string s = "";

    printLCS(n,n,s);

    for(auto tmp: st)
        cout << tmp << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Soul_97/article/details/81453156
今日推荐